Skip to content

Commit 7bcf5f0

Browse files
committed
✨ Add useCopyToClipboard hook
1 parent 05422a2 commit 7bcf5f0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// source: https://usehooks-ts.com/react-hook/use-copy-to-clipboard
2+
import { useCallback, useState } from "react"
3+
4+
type CopiedValue = string | null
5+
6+
type CopyFn = (text: string) => Promise<boolean>
7+
8+
export function useCopyToClipboard(): [CopiedValue, CopyFn] {
9+
const [copiedText, setCopiedText] = useState<CopiedValue>(null)
10+
11+
const copy: CopyFn = useCallback(async (text) => {
12+
if (!navigator?.clipboard) {
13+
console.warn("Clipboard not supported")
14+
return false
15+
}
16+
17+
try {
18+
await navigator.clipboard.writeText(text)
19+
setCopiedText(text)
20+
21+
setTimeout(() => setCopiedText(null), 2000)
22+
23+
return true
24+
} catch (error) {
25+
console.warn("Copy failed", error)
26+
setCopiedText(null)
27+
return false
28+
}
29+
}, [])
30+
31+
return [copiedText, copy]
32+
}

0 commit comments

Comments
 (0)