Skip to content

Commit 177d1d5

Browse files
committed
feat: use copy
1 parent 56ded06 commit 177d1d5

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'use client'
2+
import { useCallback, useEffect, useState } from 'react'
3+
4+
type CopiedValue = string | null
5+
6+
type CopyFn = (text: string) => Promise<boolean>
7+
8+
export function useCopyToClipboard({
9+
isCopiedDelay = 2000,
10+
}: {
11+
isCopiedDelay?: number
12+
} = {}): [CopiedValue, CopyFn, boolean] {
13+
const [copiedText, setCopiedText] = useState<CopiedValue>(null)
14+
const [isCopied, setIsCopied] = useState(false)
15+
16+
useEffect(() => {
17+
if (!isCopied) {
18+
return
19+
}
20+
setTimeout(() => {
21+
setIsCopied(false)
22+
}, isCopiedDelay)
23+
}, [isCopied, isCopiedDelay])
24+
25+
const copy: CopyFn = useCallback(async (text) => {
26+
if (!navigator?.clipboard) {
27+
return false
28+
}
29+
30+
// Try to save to clipboard then save it in the state if worked
31+
try {
32+
await navigator.clipboard.writeText(text)
33+
setCopiedText(text)
34+
setIsCopied(true)
35+
return true
36+
} catch (_error) {
37+
setCopiedText(null)
38+
return false
39+
}
40+
}, [])
41+
42+
return [copiedText, copy, isCopied]
43+
}

0 commit comments

Comments
 (0)