File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments