Skip to content

Commit 5e0b4db

Browse files
authored
fix stuc on submitting (#196)
1 parent bc52fa9 commit 5e0b4db

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

src/lib/stores.ts

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,50 @@ export const combinedGenerations = derived(
4646
)
4747

4848
combinedGenerations.subscribe((value) => {
49+
const setItemDeletingOldIfNeeded = (value: GenerationWithSource[], attempts = 0) => {
50+
// Safeguard: Prevent infinite recursion
51+
if (attempts > 1000) {
52+
console.error('Too many attempts to store generations, giving up')
53+
localStorage.removeItem(PERSIST_KEY_GENERATIONS)
54+
return
55+
}
56+
57+
// Safeguard: If we have no generations left, just clear the storage
58+
if (value.length === 0) {
59+
console.warn('No generations left to store, clearing localStorage')
60+
localStorage.removeItem(PERSIST_KEY_GENERATIONS)
61+
return
62+
}
63+
64+
try {
65+
localStorage.setItem(PERSIST_KEY_GENERATIONS, JSON.stringify(value))
66+
67+
// Log successful storage if we had to reduce items
68+
if (attempts > 0) {
69+
console.log(
70+
`Successfully stored ${value.length} generations after ${attempts + 1} attempts`
71+
)
72+
}
73+
} catch (e) {
74+
if (e instanceof DOMException && e.name === 'QuotaExceededError') {
75+
// Log the reduction attempt
76+
if (attempts === 0) {
77+
console.warn(`localStorage quota exceeded with ${value.length} generations, reducing...`)
78+
}
79+
80+
// If we hit the quota, delete the oldest generation and try again
81+
const smallerGenerations = value.slice(0, -1)
82+
setItemDeletingOldIfNeeded(smallerGenerations, attempts + 1)
83+
} else {
84+
// Handle other storage errors
85+
console.error('Non-quota localStorage error:', e)
86+
localStorage.removeItem(PERSIST_KEY_GENERATIONS)
87+
}
88+
}
89+
}
90+
4991
if (browser) {
50-
localStorage.setItem(PERSIST_KEY_GENERATIONS, JSON.stringify(value))
92+
setItemDeletingOldIfNeeded(value)
5193
}
5294
})
5395

0 commit comments

Comments
 (0)