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 { useState, useEffect } from "react";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useApiKey } from "@/hooks/use-api-key";
import { EditorToolbar } from "@/components/editor/editor-toolbar"; import { EditorToolbar } from "@/components/editor/editor-toolbar";
import { PageSidebar } from "@/components/editor/page-sidebar"; import { PageSidebar } from "@/components/editor/page-sidebar";
import { ComicCanvas } from "@/components/editor/comic-canvas"; import { ComicCanvas } from "@/components/editor/comic-canvas";
@@ -48,6 +49,7 @@ export default function StoryEditorPage() {
string[] string[]
>([]); >([]);
const { toast } = useToast(); const { toast } = useToast();
const [apiKey, setApiKey] = useApiKey();
// Load story and pages from API // Load story and pages from API
useEffect(() => { useEffect(() => {
@@ -123,8 +125,7 @@ export default function StoryEditorPage() {
}, [pages.length]); }, [pages.length]);
const handleAddPage = () => { const handleAddPage = () => {
const storedKey = localStorage.getItem("together_api_key"); if (!apiKey && pages.length >= 1) {
if (!storedKey && pages.length >= 1) {
setShowApiModal(true); setShowApiModal(true);
return; return;
} }
@@ -132,8 +133,7 @@ export default function StoryEditorPage() {
}; };
const handleRedrawPage = async () => { const handleRedrawPage = async () => {
const storedKey = localStorage.getItem("together_api_key"); if (!apiKey) {
if (!storedKey) {
setShowApiModal(true); setShowApiModal(true);
return; return;
} }
@@ -148,7 +148,7 @@ export default function StoryEditorPage() {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"x-api-key": storedKey, "x-api-key": apiKey,
}, },
body: JSON.stringify({ body: JSON.stringify({
storyId: story?.slug, storyId: story?.slug,
@@ -196,7 +196,7 @@ export default function StoryEditorPage() {
}; };
const handleApiKeySubmit = (key: string) => { const handleApiKeySubmit = (key: string) => {
localStorage.setItem("together_api_key", key); setApiKey(key);
setShowApiModal(false); setShowApiModal(false);
const wasGenerating = showGenerateModal; const wasGenerating = showGenerateModal;
if (wasGenerating) { if (wasGenerating) {
@@ -210,7 +210,6 @@ export default function StoryEditorPage() {
characterUrls?: string[]; characterUrls?: string[];
}) => { }) => {
try { try {
const apiKey = localStorage.getItem("together_api_key");
if (!apiKey) { if (!apiKey) {
setShowApiModal(true); setShowApiModal(true);
return; return;
+18 -20
View File
@@ -13,6 +13,7 @@ import {
DialogDescription, DialogDescription,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { TOGETHER_LINK } from "@/lib/utils"; import { TOGETHER_LINK } from "@/lib/utils";
import { useApiKey } from "@/hooks/use-api-key";
interface ApiKeyModalProps { interface ApiKeyModalProps {
isOpen: boolean; isOpen: boolean;
@@ -21,38 +22,35 @@ interface ApiKeyModalProps {
} }
export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) { export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
const [apiKey, setApiKey] = useState(""); const [apiKeyInput, setApiKeyInput] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [existingKey, setExistingKey] = useState<string | null>(null); const [existingKey, setApiKey] = useApiKey();
useEffect(() => { useEffect(() => {
if (typeof window !== "undefined" && isOpen) { if (isOpen) {
const storedKey = localStorage.getItem("together_api_key"); setApiKeyInput((current) => {
setExistingKey(storedKey); if (existingKey && current === "") {
setApiKey((current) => { return existingKey;
if (storedKey && current === "") {
return storedKey;
} }
return current; return current;
}); });
} }
}, [isOpen]); }, [isOpen, existingKey]);
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (!apiKey.trim()) return; if (!apiKeyInput.trim()) return;
setIsLoading(true); setIsLoading(true);
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
setIsLoading(false); setIsLoading(false);
onSubmit(apiKey.trim()); onSubmit(apiKeyInput.trim());
setApiKey(""); setApiKeyInput("");
}; };
const handleDelete = () => { const handleDelete = () => {
localStorage.removeItem("together_api_key"); setApiKey(null);
setExistingKey(null); setApiKeyInput("");
setApiKey("");
onClose(); onClose();
}; };
@@ -83,15 +81,15 @@ export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
<div className="relative"> <div className="relative">
<Input <Input
type="password" type="password"
value={apiKey} value={apiKeyInput}
onChange={(e) => setApiKey(e.target.value)} onChange={(e) => setApiKeyInput(e.target.value)}
placeholder={existingKey ? "Your current API key" : "Enter your API key..."} 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" className="bg-secondary border-border/50 text-white placeholder-muted-foreground py-5 pr-10"
/> />
{apiKey && ( {apiKeyInput && (
<button <button
type="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" 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" /> <X className="w-4 h-4" />
@@ -120,7 +118,7 @@ export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
</Button> </Button>
<Button <Button
type="submit" type="submit"
disabled={!apiKey.trim() || isLoading} disabled={!apiKeyInput.trim() || isLoading}
className="flex-1 gap-2 bg-white hover:bg-neutral-200 text-black" className="flex-1 gap-2 bg-white hover:bg-neutral-200 text-black"
> >
{isLoading ? "Validating..." : "Continue"} {isLoading ? "Validating..." : "Continue"}
+14 -14
View File
@@ -9,6 +9,7 @@ import { useS3Upload } from "next-s3-upload";
import { useAuth, SignInButton } from "@clerk/nextjs"; import { useAuth, SignInButton } from "@clerk/nextjs";
import { COMIC_STYLES } from "@/lib/constants"; import { COMIC_STYLES } from "@/lib/constants";
import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"; import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut";
import { useApiKey } from "@/hooks/use-api-key";
interface ComicCreationFormProps { interface ComicCreationFormProps {
prompt: string; prompt: string;
@@ -36,25 +37,14 @@ export function ComicCreationForm({
const { toast } = useToast(); const { toast } = useToast();
const { uploadToS3 } = useS3Upload(); const { uploadToS3 } = useS3Upload();
const { isSignedIn, isLoaded } = useAuth(); const { isSignedIn, isLoaded } = useAuth();
const [hasApiKey, setHasApiKey] = useState(false); const [apiKey] = useApiKey();
const hasApiKey = !!apiKey;
const [previews, setPreviews] = useState<string[]>([]); const [previews, setPreviews] = useState<string[]>([]);
const [showPreview, setShowPreview] = useState<number | null>(null); const [showPreview, setShowPreview] = useState<number | null>(null);
const [showStyleDropdown, setShowStyleDropdown] = useState(false); const [showStyleDropdown, setShowStyleDropdown] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(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(() => { useEffect(() => {
if (isLoading) { if (isLoading) {
@@ -138,7 +128,17 @@ export function ComicCreationForm({
setLoadingStep(0); setLoadingStep(0);
try { 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( const characterUploads = await Promise.all(
characterFiles.map((file) => uploadToS3(file).then(({ url }) => url)) 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 Link from "next/link";
import { ApiKeyModal } from "@/components/api-key-modal"; import { ApiKeyModal } from "@/components/api-key-modal";
import { SignInButton, SignedIn, SignedOut, useAuth } from "@clerk/nextjs"; import { SignInButton, SignedIn, SignedOut, useAuth } from "@clerk/nextjs";
import { useApiKey } from "@/hooks/use-api-key";
export function Navbar() { export function Navbar() {
const [showApiModal, setShowApiModal] = useState(false); const [showApiModal, setShowApiModal] = useState(false);
const { isLoaded } = useAuth(); const { isLoaded } = useAuth();
const pathname = usePathname(); const pathname = usePathname();
const [, setApiKey] = useApiKey();
const handleApiKeySubmit = (key: string) => { const handleApiKeySubmit = (key: string) => {
localStorage.setItem("together_api_key", key); setApiKey(key);
setShowApiModal(false); 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];
}