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
This commit is contained in:
Justin Edmund 2025-11-24 07:47:43 -08:00
parent 7c08daffe8
commit 2d1d344133

View file

@ -104,12 +104,17 @@
}
// Autosave store (edit mode only)
const autoSave = mode === 'edit' && album
? createAutoSaveStore({
let autoSave = $state<ReturnType<typeof createAutoSaveStore<ReturnType<typeof buildPayload>, 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<ReturnType<typeof buildPayload>>({
@ -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()
}
})