SurfSense/surfsense_web/hooks/use-api-key.ts

59 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-07-27 10:44:27 -07:00
import { useCallback, useEffect, useState } from "react";
2025-07-27 10:05:37 -07:00
import { toast } from "sonner";
import { getBearerToken } from "@/lib/auth-utils";
import { copyToClipboard as copyToClipboardUtil } from "@/lib/utils";
2025-04-07 23:47:06 -07:00
interface UseApiKeyReturn {
2025-07-27 10:05:37 -07:00
apiKey: string | null;
isLoading: boolean;
copied: boolean;
copyToClipboard: () => Promise<void>;
2025-04-07 23:47:06 -07:00
}
export function useApiKey(): UseApiKeyReturn {
2025-07-27 10:05:37 -07:00
const [apiKey, setApiKey] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Load API key from localStorage
const loadApiKey = () => {
try {
const token = getBearerToken();
2025-07-27 10:05:37 -07:00
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");
setTimeout(() => {
setCopied(false);
}, 2000);
} else {
2025-07-27 10:05:37 -07:00
toast.error("Failed to copy API key");
}
}, [apiKey]);
return {
apiKey,
isLoading,
copied,
copyToClipboard,
};
2025-12-05 00:17:31 -08:00
}