Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active May 2, 2024 02:38
Show Gist options
  • Select an option

  • Save joshnuss/aa3539daf7ca412202b4c10d543bc077 to your computer and use it in GitHub Desktop.

Select an option

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
// 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
}
}
@happysalada
Copy link

great gist!
small detail, you never use update from store. No need to define it line 9

@joshnuss
Copy link
Author

@happysalada good catch! I've updated the example 🙇

@koo5
Copy link

koo5 commented May 31, 2020

nice, care to add a license?

@joshnuss
Copy link
Author

joshnuss commented Jun 1, 2020

@koo5 good point, I've added one to this gist

@alfrednerstu
Copy link

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