Last active
January 28, 2025 15:40
-
-
Save eyeseast/ca323928045efeb0499339f109d72db6 to your computer and use it in GitHub Desktop.
A Svelte store that saves to localStorage
This file contains hidden or 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
<script> | |
import { onMount } from "svelte"; | |
import { writable } from "svelte/store"; | |
import { saveStore } from "localstorage.js"; | |
let features = writable([]) | |
onMount(() => { | |
saveStore(features, "$features", { storage: localStorage }); | |
} | |
</script> |
This file contains hidden or 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 function saveStore( | |
store, | |
key, | |
{ storage = sessionStorage, serialize = JSON.stringify, deserialize = JSON.parse } | |
) { | |
if (!store || !key) return; | |
const saved = storage.getItem(key); | |
if (saved) { | |
store.set(deserialize(saved)); | |
} | |
return store.subscribe($value => { | |
storage.setItem(key, serialize($value)); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment