modul-s / src /context /ApiKeyContext.tsx
sitcod3's picture
Upload src/context/ApiKeyContext.tsx with huggingface_hub
e66d96b verified
Raw History Blame Contribute Delete
2.57 kB
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
interface ApiKey {
id: string;
name: string;
key: string;
createdAt: string;
}
interface ApiKeyContextType {
apiKeys: ApiKey[];
activeKeyId: string | null;
activeKey: string | null;
addApiKey: (name: string, key: string) => void;
removeApiKey: (id: string) => void;
renameApiKey: (id: string, newName: string) => void;
setActiveKeyId: (id: string) => void;
}
const ApiKeyContext = createContext<ApiKeyContextType | undefined>(undefined);
export function ApiKeyProvider({ children }: { children: ReactNode }) {
const [apiKeys, setApiKeys] = useState<ApiKey[]>(() => {
const saved = localStorage.getItem("smartlead_api_keys");
return saved ? JSON.parse(saved) : [];
});
const [activeKeyId, setActiveKeyIdState] = useState<string | null>(() => {
return localStorage.getItem("smartlead_active_key_id");
});
useEffect(() => {
localStorage.setItem("smartlead_api_keys", JSON.stringify(apiKeys));
}, [apiKeys]);
useEffect(() => {
if (activeKeyId) {
localStorage.setItem("smartlead_active_key_id", activeKeyId);
} else {
localStorage.removeItem("smartlead_active_key_id");
}
}, [activeKeyId]);
const addApiKey = (name: string, key: string) => {
const newKey: ApiKey = {
id: Math.random().toString(36).substring(7),
name,
key,
createdAt: new Date().toISOString()
};
setApiKeys((prev) => [...prev, newKey]);
if (!activeKeyId) {
setActiveKeyIdState(newKey.id);
}
};
const removeApiKey = (id: string) => {
setApiKeys((prev) => prev.filter((k) => k.id !== id));
if (activeKeyId === id) {
setActiveKeyIdState(null);
}
};
const renameApiKey = (id: string, newName: string) => {
setApiKeys((prev) => prev.map((k) => k.id === id ? { ...k, name: newName } : k));
};
const activeKey = apiKeys.find((k) => k.id === activeKeyId)?.key || null;
return (
<ApiKeyContext.Provider
value={{
apiKeys,
activeKeyId,
activeKey,
addApiKey,
removeApiKey,
renameApiKey,
setActiveKeyId: setActiveKeyIdState,
}}
>
{children}
</ApiKeyContext.Provider>
);
}
export function useApiKey() {
const context = useContext(ApiKeyContext);
if (context === undefined) {
throw new Error("useApiKey must be used within an ApiKeyProvider");
}
return context;
}