use-clipboard.ts 986 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use client";
  2. import React from "react";
  3. function useClipboard({ timeout = 2000 } = {}) {
  4. const [error, setError] = React.useState<Error | null>(null)
  5. const [copied, setCopied] = React.useState(false)
  6. const [copyTimeout, setCopyTimeout] = React.useState<NodeJS.Timeout | null>(null)
  7. const handleCopyResult = (value: boolean) => {
  8. copyTimeout && clearTimeout(copyTimeout)
  9. setCopyTimeout(setTimeout(() => setCopied(false), timeout))
  10. setCopied(value)
  11. }
  12. const copy = (valueToCopy: string) => {
  13. if ("clipboard" in navigator) {
  14. navigator.clipboard
  15. .writeText(valueToCopy)
  16. .then(() => handleCopyResult(true))
  17. .catch((err) => setError(err))
  18. } else {
  19. setError(new Error("useClipboard: navigator.clipboard is not supported"))
  20. }
  21. }
  22. const reset = () => {
  23. setCopied(false)
  24. setError(null)
  25. copyTimeout && clearTimeout(copyTimeout)
  26. }
  27. return { copy, reset, error, copied }
  28. }
  29. export default useClipboard