Created
August 26, 2020 18:49
-
-
Save tillbaks/e04bb3503316c8863b1757e4159cd08f to your computer and use it in GitHub Desktop.
Svelte writable store that stores its value in localStorage. Does json parsing and stringifying if initial value is an object/array.
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
import { writable } from "svelte/store"; | |
/** | |
* Svelte writable store that stores its value in localStorage. | |
* Does json parsing and stringifying if initial value is an object/array. | |
* | |
* @param {string} key localStorage-key | |
* @param {string|number|boolean|object|array} initialValue the initial value of the store (also the value that can be reset to with the reset() function) | |
**/ | |
export const storable = (key, initialValue) => { | |
const storeAsJSON = typeof initialValue === "object"; | |
function getStoreValue() { | |
const storeValue = localStorage.getItem(key); | |
if (storeAsJSON) { | |
try { | |
return JSON.parse(storeValue); | |
} catch (ignored) { | |
return initialValue; | |
} | |
} | |
return storeValue !== undefined ? storeValue : initialValue; | |
} | |
const { set, update, subscribe } = writable(getStoreValue()); | |
subscribe((value) => | |
localStorage.setItem(key, storeAsJSON ? JSON.stringify(value) : value) | |
); | |
return { | |
set, | |
update, | |
subscribe, | |
reset() { | |
set(initialValue); | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment