Last active
May 2, 2024 02:38
-
-
Save joshnuss/aa3539daf7ca412202b4c10d543bc077 to your computer and use it in GitHub Desktop.
LocalStorage store for Svelte.js. NPM Package: https://github.com/joshnuss/svelte-local-storage-store
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
| // Svelte store backed by window.localStorage | |
| // Persists store's data locally | |
| import {writable as internal, get} from 'svelte/store' | |
| export function writable(key, initialValue) { | |
| const store = internal(initialValue) | |
| const {subscribe, set, update} = store | |
| const json = localStorage.getItem(key) | |
| if (json) { | |
| set(JSON.parse(json)) | |
| } | |
| return { | |
| set(value) { | |
| localStorage.setItem(key, JSON.stringify(value)) | |
| set(value) | |
| }, | |
| update(cb) { | |
| const value = cb(get(store)) | |
| this.set(value) | |
| }, | |
| subscribe | |
| } | |
| } |
Author
@happysalada good catch! I've updated the example 🙇
nice, care to add a license?
Author
@koo5 good point, I've added one to this gist
I had to add if(process.browser) to make it work in my Sapper setup. Without it the server crashed and I got ReferenceError: localStorage is not defined.
if(process.browser) {
const json = localStorage.getItem(key)
// use the value from localStorage if it exists
if (json) {
set(JSON.parse(json))
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great gist!
small detail, you never use update from store. No need to define it line 9