All files / app/utils useCopyToClipboard.ts

95.65% Statements 22/23
80% Branches 4/5
100% Functions 4/4
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 449x           54x 54x 54x 54x   54x 37x 37x         54x     7x   7x 4x     3x   7x 7x 7x 7x 1x 1x   7x         54x    
import { useCallback, useEffect, useRef, useState } from "react";
 
type CopyStatus = "idle" | "copied" | "failed";
 
// status goes back to "idle" after resetAfterMs, so feedback like "Copied!" can be shown temporarily
// copy resolves to whether it succeeded
export default function useCopyToClipboard(resetAfterMs = 2000) {
  const [status, setStatus] = useState<CopyStatus>("idle");
  const [copiedText, setCopiedText] = useState<string | null>(null);
  const timer = useRef<number | null>(null);
 
  useEffect(
    () => () => {
      if (timer.current) window.clearTimeout(timer.current);
    },
    [],
  );
 
  const copy = useCallback(
    async (text: string) => {
      let result: CopyStatus;
      try {
        // clipboard is undefined outside secure contexts, which throws here too
        await navigator.clipboard.writeText(text);
        result = "copied";
      } catch {
        // shown to the user instead of thrown: the browser or user can deny clipboard access
        result = "failed";
      }
      setStatus(result);
      setCopiedText(text);
      Iif (timer.current) window.clearTimeout(timer.current);
      timer.current = window.setTimeout(() => {
        setStatus("idle");
        setCopiedText(null);
      }, resetAfterMs);
      return result === "copied";
    },
    [resetAfterMs],
  );
 
  return { copy, status, copiedText };
}