forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseClipboard.ts
41 lines (36 loc) · 897 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
37
38
39
40
41
import { useState, useEffect } from 'react'
interface IOptions {
/**
* Reset the status after a certain number of milliseconds. This is useful
* for showing a temporary success message.
*/
successDuration?: number
}
export default function useCopyClipboard(
text: string,
options?: IOptions
): [boolean, () => Promise<void>] {
const [isCopied, setIsCopied] = useState(false)
const successDuration = options && options.successDuration
useEffect(() => {
if (isCopied && successDuration) {
const id = setTimeout(() => {
setIsCopied(false)
}, successDuration)
return () => {
clearTimeout(id)
}
}
}, [isCopied, successDuration])
return [
isCopied,
async () => {
try {
await navigator.clipboard.writeText(text)
setIsCopied(true)
} catch {
setIsCopied(false)
}
},
]
}