Replace localStorage API key with reactive hook across app

This commit is contained in:
Riccardo Giorato
2025-12-26 21:16:23 +01:00
parent 0ff8a4e685
commit b4503b7e3e
5 changed files with 106 additions and 42 deletions
+6 -7
View File
@@ -3,6 +3,7 @@
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import { useToast } from "@/hooks/use-toast";
import { useApiKey } from "@/hooks/use-api-key";
import { EditorToolbar } from "@/components/editor/editor-toolbar";
import { PageSidebar } from "@/components/editor/page-sidebar";
import { ComicCanvas } from "@/components/editor/comic-canvas";
@@ -48,6 +49,7 @@ export default function StoryEditorPage() {
string[]
>([]);
const { toast } = useToast();
const [apiKey, setApiKey] = useApiKey();
// Load story and pages from API
useEffect(() => {
@@ -123,8 +125,7 @@ export default function StoryEditorPage() {
}, [pages.length]);
const handleAddPage = () => {
const storedKey = localStorage.getItem("together_api_key");
if (!storedKey && pages.length >= 1) {
if (!apiKey && pages.length >= 1) {
setShowApiModal(true);
return;
}
@@ -132,8 +133,7 @@ export default function StoryEditorPage() {
};
const handleRedrawPage = async () => {
const storedKey = localStorage.getItem("together_api_key");
if (!storedKey) {
if (!apiKey) {
setShowApiModal(true);
return;
}
@@ -148,7 +148,7 @@ export default function StoryEditorPage() {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": storedKey,
"x-api-key": apiKey,
},
body: JSON.stringify({
storyId: story?.slug,
@@ -196,7 +196,7 @@ export default function StoryEditorPage() {
};
const handleApiKeySubmit = (key: string) => {
localStorage.setItem("together_api_key", key);
setApiKey(key);
setShowApiModal(false);
const wasGenerating = showGenerateModal;
if (wasGenerating) {
@@ -210,7 +210,6 @@ export default function StoryEditorPage() {
characterUrls?: string[];
}) => {
try {
const apiKey = localStorage.getItem("together_api_key");
if (!apiKey) {
setShowApiModal(true);
return;
+18 -20
View File
@@ -13,6 +13,7 @@ import {
DialogDescription,
} from "@/components/ui/dialog";
import { TOGETHER_LINK } from "@/lib/utils";
import { useApiKey } from "@/hooks/use-api-key";
interface ApiKeyModalProps {
isOpen: boolean;
@@ -21,38 +22,35 @@ interface ApiKeyModalProps {
}
export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
const [apiKey, setApiKey] = useState("");
const [apiKeyInput, setApiKeyInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [existingKey, setExistingKey] = useState<string | null>(null);
const [existingKey, setApiKey] = useApiKey();
useEffect(() => {
if (typeof window !== "undefined" && isOpen) {
const storedKey = localStorage.getItem("together_api_key");
setExistingKey(storedKey);
setApiKey((current) => {
if (storedKey && current === "") {
return storedKey;
if (isOpen) {
setApiKeyInput((current) => {
if (existingKey && current === "") {
return existingKey;
}
return current;
});
}
}, [isOpen]);
}, [isOpen, existingKey]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!apiKey.trim()) return;
if (!apiKeyInput.trim()) return;
setIsLoading(true);
await new Promise((resolve) => setTimeout(resolve, 500));
setIsLoading(false);
onSubmit(apiKey.trim());
setApiKey("");
onSubmit(apiKeyInput.trim());
setApiKeyInput("");
};
const handleDelete = () => {
localStorage.removeItem("together_api_key");
setExistingKey(null);
setApiKey("");
setApiKey(null);
setApiKeyInput("");
onClose();
};
@@ -83,15 +81,15 @@ export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
<div className="relative">
<Input
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
value={apiKeyInput}
onChange={(e) => setApiKeyInput(e.target.value)}
placeholder={existingKey ? "Your current API key" : "Enter your API key..."}
className="bg-secondary border-border/50 text-white placeholder-muted-foreground py-5 pr-10"
/>
{apiKey && (
{apiKeyInput && (
<button
type="button"
onClick={() => setApiKey("")}
onClick={() => setApiKeyInput("")}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-white transition-colors"
>
<X className="w-4 h-4" />
@@ -120,7 +118,7 @@ export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
</Button>
<Button
type="submit"
disabled={!apiKey.trim() || isLoading}
disabled={!apiKeyInput.trim() || isLoading}
className="flex-1 gap-2 bg-white hover:bg-neutral-200 text-black"
>
{isLoading ? "Validating..." : "Continue"}
+14 -14
View File
@@ -9,6 +9,7 @@ import { useS3Upload } from "next-s3-upload";
import { useAuth, SignInButton } from "@clerk/nextjs";
import { COMIC_STYLES } from "@/lib/constants";
import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut";
import { useApiKey } from "@/hooks/use-api-key";
interface ComicCreationFormProps {
prompt: string;
@@ -36,25 +37,14 @@ export function ComicCreationForm({
const { toast } = useToast();
const { uploadToS3 } = useS3Upload();
const { isSignedIn, isLoaded } = useAuth();
const [hasApiKey, setHasApiKey] = useState(false);
const [apiKey] = useApiKey();
const hasApiKey = !!apiKey;
const [previews, setPreviews] = useState<string[]>([]);
const [showPreview, setShowPreview] = useState<number | null>(null);
const [showStyleDropdown, setShowStyleDropdown] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Check if user has their own API key set
useEffect(() => {
const checkApiKey = () => {
const apiKey = localStorage.getItem("together_api_key");
setHasApiKey(!!apiKey);
};
checkApiKey();
// Listen for storage changes
window.addEventListener("storage", checkApiKey);
return () => window.removeEventListener("storage", checkApiKey);
}, []);
useEffect(() => {
if (isLoading) {
@@ -138,7 +128,17 @@ export function ComicCreationForm({
setLoadingStep(0);
try {
const apiKey = localStorage.getItem("together_api_key");
if (!apiKey) {
toast({
title: "API key required",
description: "Please add your API key to generate comics.",
variant: "destructive",
duration: 3000,
});
setIsLoading(false);
return;
}
const characterUploads = await Promise.all(
characterFiles.map((file) => uploadToS3(file).then(({ url }) => url))
);
+3 -1
View File
@@ -6,15 +6,17 @@ import { Github, Key, BookOpen, User, Plus } from "lucide-react";
import Link from "next/link";
import { ApiKeyModal } from "@/components/api-key-modal";
import { SignInButton, SignedIn, SignedOut, useAuth } from "@clerk/nextjs";
import { useApiKey } from "@/hooks/use-api-key";
export function Navbar() {
const [showApiModal, setShowApiModal] = useState(false);
const { isLoaded } = useAuth();
const pathname = usePathname();
const [, setApiKey] = useApiKey();
const handleApiKeySubmit = (key: string) => {
localStorage.setItem("together_api_key", key);
setApiKey(key);
setShowApiModal(false);
};
+65
View File
@@ -0,0 +1,65 @@
"use client";
import { useState, useEffect, useCallback } from "react";
const STORAGE_KEY = "together_api_key";
const STORAGE_EVENT = "apiKeyChanged";
/**
* Reactive hook for managing the Together API key in localStorage.
* Automatically syncs across components and tabs when the key changes.
*
* @returns {[string | null, (key: string | null) => void]} Tuple of [apiKey, setApiKey]
*/
export function useApiKey(): [string | null, (key: string | null) => void] {
const [apiKey, setApiKeyState] = useState<string | null>(null);
// Initialize from localStorage on mount
useEffect(() => {
const readFromStorage = () => {
if (typeof window !== "undefined") {
const stored = localStorage.getItem(STORAGE_KEY);
setApiKeyState(stored);
}
};
readFromStorage();
// Listen for storage events (cross-tab updates)
const handleStorageChange = (e: StorageEvent) => {
if (e.key === STORAGE_KEY) {
setApiKeyState(e.newValue);
}
};
// Listen for custom events (same-tab updates)
const handleCustomStorageChange = () => {
readFromStorage();
};
window.addEventListener("storage", handleStorageChange);
window.addEventListener(STORAGE_EVENT, handleCustomStorageChange);
return () => {
window.removeEventListener("storage", handleStorageChange);
window.removeEventListener(STORAGE_EVENT, handleCustomStorageChange);
};
}, []);
// Setter function that updates both localStorage and state, and dispatches event
const setApiKey = useCallback((key: string | null) => {
if (typeof window !== "undefined") {
if (key === null) {
localStorage.removeItem(STORAGE_KEY);
} else {
localStorage.setItem(STORAGE_KEY, key);
}
setApiKeyState(key);
// Dispatch custom event for same-tab reactivity
window.dispatchEvent(new CustomEvent(STORAGE_EVENT));
}
}, []);
return [apiKey, setApiKey];
}