Last active
August 30, 2020 12:30
-
-
Save arxpoetica/350c22518af08af0f8077c2f8c9b75e3 to your computer and use it in GitHub Desktop.
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
/* 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