useCopyToClipboard.ts46 lines · main
| 1 | import { useCallback, useState } from 'react' |
| 2 | import { toast } from 'sonner' |
| 3 | |
| 4 | // [Joshen] This hook can replace all usage of copyToClipboard from lib/helpers |
| 5 | export function useCopyToClipboard() { |
| 6 | const [text, setText] = useState<string | null>(null) |
| 7 | |
| 8 | const copy = useCallback( |
| 9 | async ( |
| 10 | text: string, |
| 11 | { timeout, withToast }: { timeout?: number; withToast?: boolean } = { |
| 12 | timeout: 3000, |
| 13 | withToast: false, |
| 14 | } |
| 15 | ) => { |
| 16 | if (!navigator?.clipboard) { |
| 17 | console.warn('Clipboard not supported') |
| 18 | return false |
| 19 | } |
| 20 | |
| 21 | try { |
| 22 | await navigator.clipboard.writeText(text) |
| 23 | setText(text) |
| 24 | |
| 25 | if (timeout) { |
| 26 | setTimeout(() => { |
| 27 | setText(null) |
| 28 | }, timeout) |
| 29 | } |
| 30 | |
| 31 | if (withToast) { |
| 32 | toast.success('Copied to clipboard') |
| 33 | } |
| 34 | |
| 35 | return true |
| 36 | } catch (error) { |
| 37 | console.warn('Copy failed', error) |
| 38 | setText(null) |
| 39 | return false |
| 40 | } |
| 41 | }, |
| 42 | [] |
| 43 | ) |
| 44 | |
| 45 | return { text, copy, isCopied: text !== null } |
| 46 | } |