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'
// wraps a regular writable store
export function writable(key, initialValue) {
// create an underlying store
const store = internal(initialValue)
const {subscribe, set} = store
// get the last value from localStorage
const json = localStorage.getItem(key)
// use the value from localStorage if it exists
if (json) {
set(JSON.parse(json))
}
// return an object with the same interface as svelte's writable()
return {
// capture set and write to localStorage
set(value) {
localStorage.setItem(key, JSON.stringify(value))
set(value)
},
// capture updates and write to localStore
update(cb) {
const value = cb(get(store))
this.set(value)
},
// punt subscriptions to underlying store
subscribe
}
}
// define your stores
import { writable } from './localStorageStore'
// `preferences` will be:
// - Synced with localStorage
// - Accessible via pub/sub
export const preferences = writable('preferences', {
theme: 'dark',
pane: '50%',
...
})
// then when you want to use the store
import { get } from 'svelte/store'
import { preferences } from './stores'
preferences.subscribe(...) // subscribe to changes
preferences.update(...) // update value
preferences.set(...) // set value
get(preferences) // read value
$preferences // read value with automatic subscription
@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