useCopyToClipboard
ratneshc/use-copy-to-clipboardFreeHook
ratneshc publishes no description for this item.
Install it
npx shadcn@latest add https://ratneshc.com/r/use-copy-to-clipboard.jsonSource
1// Thanks @ncdai23"use client";45import * as React from "react";67export type CopyState = "idle" | "done" | "error";89export type UseCopyToClipboardOptions = {10 /** Called when the text is successfully copied. */11 onCopySuccess?: (text: string) => void;12 /** Called when the copy operation fails. */13 onCopyError?: (error: Error) => void;14 /** The delay in milliseconds before resetting the state to "idle". Defaults to 1500. */15 resetDelay?: number;16};1718export function useCopyToClipboard({19 onCopySuccess,20 onCopyError,21 resetDelay = 1500,22}: UseCopyToClipboardOptions = {}) {23 const [state, setState] = React.useState<CopyState>("idle");24 const resetTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(25 null26 );2728 const copy = React.useCallback(29 async (text: string | (() => string)) => {30 // Clear any pending reset31 if (resetTimeoutRef.current) {32 clearTimeout(resetTimeoutRef.current);33 }3435 try {36 const finalText = typeof text === "function" ? text() : text;37 await navigator.clipboard.writeText(finalText);3839 setState("done");4041 onCopySuccess?.(finalText);42 } catch (error) {43 setState("error");4445 onCopyError?.(46 error instanceof Error ? error : new Error("Copy failed")47 );48 } finally {49 // Schedule reset to idle50 resetTimeoutRef.current = setTimeout(() => {51 setState("idle");52 }, resetDelay);53 }54 },55 [onCopySuccess, onCopyError, resetDelay]56 );5758 return { state, copy } as const;59}
