Skip to content

Instantly share code, notes, and snippets.

@arxpoetica
Last active August 30, 2020 12:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arxpoetica/350c22518af08af0f8077c2f8c9b75e3 to your computer and use it in GitHub Desktop.
Save arxpoetica/350c22518af08af0f8077c2f8c9b75e3 to your computer and use it in GitHub Desktop.
/* global localStorage */
import { writable } from 'svelte/store'
const storage = typeof localStorage !== 'undefined' ? localStorage : {
removeItem: key => { if (storage[key]) { delete storage[key] } },
}
/**
* Tracks storage both in `localStorage` and in svelte's `writable` stores
* Usage: `const name = storable('name', 'arxpoetica')`
* @param {string} key - `localStorage` key
* @param {any} value - default/initial value (if value is already set in `localStorage`, it will load that value instead)
* @param {Function} fn - handed off to `writable`
*/
export const storable = (key, value, fn) => {
key = `namespace.${key}`
if (storage[key]) { value = JSON.parse(storage[key]) }
const store = writable(value, fn)
store.subscribe(value => {
if (value === undefined) {
storage.removeItem(key)
} else {
storage[key] = JSON.stringify(value)
}
})
store.remove = () => store.set(undefined)
return store
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment