Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

feat(ui): add "useCopyToClipboard" hook with configurable timeout

unrenamed641621d077af
diff --git a/packages/ui/src/hooks/index.ts b/packages/ui/src/hooks/index.ts
index 82924adba7..e8fc7784de 100644
--- a/packages/ui/src/hooks/index.ts
+++ b/packages/ui/src/hooks/index.ts
@@ -1,4 +1,5 @@
export * from "./use-cookies";
+export * from "./use-copy-to-clipboard";
export * from "./use-current-anchor";
export * from "./use-enter-submit";
export * from "./use-in-viewport";
diff --git a/packages/ui/src/hooks/use-copy-to-clipboard.tsx b/packages/ui/src/hooks/use-copy-to-clipboard.tsx
new file mode 100644
index 0000000000..714707e602
--- /dev/null
+++ b/packages/ui/src/hooks/use-copy-to-clipboard.tsx
@@ -0,0 +1,44 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export const useCopyToClipboard = (
+ timeout: number = 3000,
+): [boolean, (value: string | ClipboardItem) => Promise<void>] => {
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const [copied, setCopied] = useState(false);
+
+ const clearTimer = () => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ timer.current = null;
+ }
+ };
+
+ const copyToClipboard = useCallback(
+ async (value: string | ClipboardItem) => {
+ clearTimer();
+ try {
+ if (typeof value === "string") {
+ await navigator.clipboard.writeText(value);
+ } else if (value instanceof ClipboardItem) {
+ await navigator.clipboard.write([value]);
+ }
+ setCopied(true);
+
+ // Ensure timeout is a non-negative finite number
+ if (Number.isFinite(timeout) && timeout >= 0) {
+ timer.current = setTimeout(() => setCopied(false), timeout);
+ }
+ } catch (error) {
+ console.error("Failed to copy: ", error);
+ }
+ },
+ [timeout],
+ );
+
+ // Cleanup the timer when the component unmounts
+ useEffect(() => {
+ return () => clearTimer();
+ }, []);
+
+ return [copied, copyToClipboard];
+};