Handle try catch on parse
asjir opened this issue · comments
Currently changing the serializer (from json to devalue in my case) is messy, because as long as someone can have stale data, you need to do this (I'm also posting in case other people face this problem):
const browser = typeof window !== "undefined" && typeof document !== "undefined" // for SSR
if (browser)
try {
serializer.parse(localStorage.get(key))
} catch {
localStorage.setItem(key, "") # removeItem didnt work for me
}
store = persisted(key, defaults, { serializer })
And I found the fact that onError
only catches read errors and not parse errors misleading which cost me extra time.
Both these problems would be solved by simply adding another option
onParseError
defaulting to rethrowing, that you could supply with your default value - then autocomplete would also make it clear that onError
doesn't include parsing errors.
Perhaps onParseError
could be passed the serialised string to have the option open for falling back to the old parser, but I wouldn't have used it.
Edit:
I settled on:
import { persisted as _persisted, type Options } from "svelte-persisted-store"
import type { Writable } from "svelte/store"
export const persisted = <T>(key: string, d: T, o?: Options<T>): Writable<T> => {
try {
return _persisted(key, d, o)
} catch {
localStorage.setItem(key, "")
return _persisted(key, d, o)
}
}
Is fixed by #246, just awaiting merge
Edit: Is now fixed and available, see readme for syntax
Closing, as @bertmad3400 mentioned, there is now a solution for this.