SurfSense/surfsense_web/hooks/use-api-key.ts
ClawdBot 805eacb9fc fix(react): Add cancelAnimationFrame cleanup in useEffect
- Add cleanup function to cancel animation frame on unmount
- Prevents potential memory leaks and setState on unmounted component
- Closes #1093
2026-04-04 02:25:56 +03:00

63 lines
1.5 KiB
TypeScript

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { getBearerToken } from "@/lib/auth-utils";
import { copyToClipboard as copyToClipboardUtil } from "@/lib/utils";
interface UseApiKeyReturn {
apiKey: string | null;
isLoading: boolean;
copied: boolean;
copyToClipboard: () => Promise<void>;
}
export function useApiKey(): UseApiKeyReturn {
const [apiKey, setApiKey] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [isLoading, setIsLoading] = useState(true);
// Clear copied state after 2 seconds
useEffect(() => {
if (copied) {
const timer = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(timer);
}
}, [copied]);
useEffect(() => {
// Load API key from localStorage
const loadApiKey = () => {
try {
const token = getBearerToken();
setApiKey(token);
} catch (error) {
console.error("Error loading API key:", error);
toast.error("Failed to load API key");
} finally {
setIsLoading(false);
}
};
// Add a small delay to simulate loading
const timer = setTimeout(loadApiKey, 500);
return () => clearTimeout(timer);
}, []);
const copyToClipboard = useCallback(async () => {
if (!apiKey) return;
const success = await copyToClipboardUtil(apiKey);
if (success) {
setCopied(true);
toast.success("API key copied to clipboard");
} else {
toast.error("Failed to copy API key");
}
}, [apiKey]);
return {
apiKey,
isLoading,
copied,
copyToClipboard,
};
}