Skip to content

Instantly share code, notes, and snippets.

@secretgspot
Created December 29, 2019 00:46
Show Gist options
  • Save secretgspot/0b8d64e9573e48dbc9f8e52ffaa0e492 to your computer and use it in GitHub Desktop.
Save secretgspot/0b8d64e9573e48dbc9f8e52ffaa0e492 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