-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-copy-to-clipboard.ts
42 lines (34 loc) · 1.16 KB
/
use-copy-to-clipboard.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"use client";
import { useCallback, useEffect, useState } from "react";
import { config } from "@/config";
import { log, oldSchoolCopy } from "../utils";
/**
* @param timeoutMilliseconds - The number of milliseconds to wait before clearing the copied value. Set to `undefined` to disable.
*
* @returns A tuple containing the copied value and a function to copy a value to the clipboard
*
* @example
* const [copied, copyToClipboard] = useCopyToClipboard();
*/
export function useCopyToClipboard(
timeoutMilliseconds = config.defaults.copyTimeoutMs,
) {
const [state, setState] = useState<string>();
// Effect: Clear copied value after timeout
useEffect(() => {
if (!state || !timeoutMilliseconds) return;
const timeout = setTimeout(() => setState(undefined), timeoutMilliseconds);
return () => clearTimeout(timeout);
}, [state, timeoutMilliseconds]);
const copyToClipboard = useCallback(async (value: string) => {
try {
await navigator?.clipboard?.writeText(value);
setState(value);
} catch (e) {
log.error(e);
oldSchoolCopy(value);
setState(value);
}
}, []);
return [state, copyToClipboard] as const;
}