-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseClipboard.ts
33 lines (28 loc) · 973 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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from 'react'
export function useClipboard({ timeout = 2000 } = {}) {
const [error, setError] = useState<Error | null>(null)
const [copied, setCopied] = useState(false)
const [copyTimeout, setCopyTimeout] = useState<number | null>(null)
const handleCopyResult = (value: boolean) => {
window.clearTimeout(copyTimeout!)
setCopyTimeout(window.setTimeout(() => setCopied(false), timeout))
setCopied(value)
}
const copy = (valueToCopy: any) => {
if ('clipboard' in navigator) {
navigator.clipboard
.writeText(valueToCopy)
.then(() => handleCopyResult(true))
.catch((err) => setError(err))
} else {
setError(new Error('useClipboard: navigator.clipboard is not supported'))
}
}
const reset = () => {
setCopied(false)
setError(null)
window.clearTimeout(copyTimeout!)
}
return { copy, reset, error, copied }
}