Last active
June 19, 2023 20:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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