Skip to content

Instantly share code, notes, and snippets.

@webcrawls
Last active June 19, 2023 20:18
Show Gist options
  • Save webcrawls/3ed220e214a94c9047e538f15d6127d0 to your computer and use it in GitHub Desktop.
Save webcrawls/3ed220e214a94c9047e538f15d6127d0 to your computer and use it in GitHub Desktop.
A Svelte store backed by the browser's localStorage. Supports custom serializer and deserializer functions.
export const localStore = <T = any>(key: string,
value: T,
deserializer: (value: string) => T = JSON.parse,
serializer: (value: T) => string = JSON.stringify): Writable<T> => {
const {subscribe, set: initialSet, update: initialUpdate} = writable<T>()
const loadValue = (): string | null => browser ? localStorage.getItem(key) : null
const saveValue = (value: string) => browser && localStorage.setItem(key, value)
const initialValue = loadValue()
initialSet(initialValue ? deserializer(initialValue) : value)
const set = (newValue: T) => {
value = newValue
initialSet(newValue)
if (newValue) saveValue(serializer(newValue))
}
const update = (fn: Updater<T>): void => {
set(fn(value))
}
return {subscribe, set, update}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment