File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ // source: https://usehooks-ts.com/react-hook/use-copy-to-clipboard
2+ import { useCallback , useState } from "react"
3+
4+ type CopiedValue = string | null
5+
6+ type CopyFn = ( text : string ) => Promise < boolean >
7+
8+ export function useCopyToClipboard ( ) : [ CopiedValue , CopyFn ] {
9+ const [ copiedText , setCopiedText ] = useState < CopiedValue > ( null )
10+
11+ const copy : CopyFn = useCallback ( async ( text ) => {
12+ if ( ! navigator ?. clipboard ) {
13+ console . warn ( "Clipboard not supported" )
14+ return false
15+ }
16+
17+ try {
18+ await navigator . clipboard . writeText ( text )
19+ setCopiedText ( text )
20+
21+ setTimeout ( ( ) => setCopiedText ( null ) , 2000 )
22+
23+ return true
24+ } catch ( error ) {
25+ console . warn ( "Copy failed" , error )
26+ setCopiedText ( null )
27+ return false
28+ }
29+ } , [ ] )
30+
31+ return [ copiedText , copy ]
32+ }
You can’t perform that action at this time.
0 commit comments