-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseClipboard.ts
36 lines (30 loc) · 869 Bytes
/
useClipboard.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
import { useCallback, useState } from 'react';
/**
* Provides functionality to copy text to the clipboard.
*
* @returns An object containing the copied text and a function to copy text to the clipboard.
*/
const useClipboard = () => {
const [copiedText, setCopiedText] = useState<string | null>(null);
const copyToClipboard = useCallback(async (text: string) => {
if (!navigator.clipboard as boolean) {
console.warn('Clipboard is not supported');
return;
}
await navigator.clipboard
.writeText(text)
.then(() => {
console.log('Copied to clipboard:', text);
setCopiedText(text);
})
.catch((error: unknown) => {
console.warn('Failed to copy', error);
setCopiedText(null);
});
}, []);
return {
copiedText,
copyToClipboard,
};
};
export default useClipboard;