File tree Expand file tree Collapse file tree
src/components/stateless/CopyToClipboard Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments