Skip to content

Commit 9def832

Browse files
committed
feat: create usehooks-ts based useClipboard hook
1 parent 6ba48e4 commit 9def832

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/hooks/useClipboard.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { useState } from "react"
2+
import { useCopyToClipboard } from "usehooks-ts"
3+
4+
type UseClipboardOptions = {
5+
/**
6+
* timeout delay (in ms) to switch back to initial state once copied.
7+
*/
8+
timeout?: number
9+
}
10+
11+
type UseClipboardReturn = {
12+
value: string
13+
setValue: React.Dispatch<React.SetStateAction<string>>
14+
onCopy: () => void
15+
hasCopied: boolean
16+
}
17+
18+
export const useClipboard = (
19+
value: string,
20+
{ timeout }: UseClipboardOptions = {}
21+
): UseClipboardReturn => {
22+
const [copyValue, setCopyValue] = useState(value)
23+
const [hasCopied, setHasCopied] = useState(false)
24+
const [_, copy] = useCopyToClipboard()
25+
26+
const onCopy = () => {
27+
copy(value)
28+
.then(() => {
29+
setHasCopied(true)
30+
setTimeout(() => {
31+
setHasCopied(false)
32+
}, timeout || 1500)
33+
})
34+
.catch((error) => {
35+
console.error("Failed to copy!", error)
36+
})
37+
}
38+
39+
return { onCopy, hasCopied, value: copyValue, setValue: setCopyValue }
40+
}

0 commit comments

Comments
 (0)