Created
March 27, 2024 17:02
-
-
Save danybeltran/e01baf55fd40f56d2a94d797ebe27916 to your computer and use it in GitHub Desktop.
Create a Writable localStorage store that allows both updating and reading by subscription
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
import { writable } from 'svelte/store' | |
const storedKeys: any = {} | |
/** | |
* Create a Writable localStorage store that allows both updating and reading by subscription | |
*/ | |
export function storable<T>(initialValue: T) { | |
const storedKey = `$-${Object.keys(storedKeys).length}` | |
storedKeys[storedKey] = true | |
const store = writable(initialValue) | |
try { | |
store.set(JSON.parse(localStorage.getItem(storedKey)!) || initialValue) | |
store.subscribe(value => { | |
localStorage.setItem(storedKey, JSON.stringify(value || initialValue)) | |
}) | |
} catch {} | |
return store | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: