useCopyToClipboard.ts 1.0 KB

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