From 2d1d3441334c3e9bf7b318a7a040da0af0721235 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Mon, 24 Nov 2025 07:47:43 -0800 Subject: [PATCH] fix: Make AlbumForm autosave reactive to album prop Changed autosave from const to reactive $state that initializes when album becomes available. This ensures autosave works even if album is null initially. Changes: - Moved autosave creation into $effect that runs when album is available - Captured album.id in local variable to avoid null reference issues - Moved useFormGuards call into same effect for proper initialization - Fixed cleanup effect to capture autoSave instance in closure - Added proper TypeScript typing for autoSave state --- src/lib/components/admin/AlbumForm.svelte | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/lib/components/admin/AlbumForm.svelte b/src/lib/components/admin/AlbumForm.svelte index bdebf97..ba68d09 100644 --- a/src/lib/components/admin/AlbumForm.svelte +++ b/src/lib/components/admin/AlbumForm.svelte @@ -104,12 +104,17 @@ } // Autosave store (edit mode only) - const autoSave = mode === 'edit' && album - ? createAutoSaveStore({ + let autoSave = $state, Album>> | null>(null) + + $effect(() => { + // Create or update autoSave when album becomes available + if (mode === 'edit' && album && !autoSave) { + const albumId = album.id // Capture album ID to avoid null reference + autoSave = createAutoSaveStore({ debounceMs: 2000, getPayload: () => (hasLoaded ? buildPayload() : null), save: async (payload, { signal }) => { - const response = await fetch(`/api/albums/${album.id}`, { + const response = await fetch(`/api/albums/${albumId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), @@ -126,7 +131,11 @@ if (draftKey) clearDraft(draftKey) } }) - : null + + // Form guards (navigation protection, Cmd+S, beforeunload) + useFormGuards(autoSave) + } + }) // Draft recovery helper const draftRecovery = useDraftRecovery>({ @@ -142,9 +151,6 @@ } }) - // Form guards (navigation protection, Cmd+S, beforeunload) - useFormGuards(autoSave) - // Watch for album changes and populate form data $effect(() => { if (album && mode === 'edit') { @@ -201,7 +207,8 @@ // Cleanup autosave on unmount $effect(() => { if (autoSave) { - return () => autoSave.destroy() + const instance = autoSave + return () => instance.destroy() } })