Skip to content

Instantly share code, notes, and snippets.

@tillbaks
Created August 26, 2020 18:49
Show Gist options
  • Save tillbaks/e04bb3503316c8863b1757e4159cd08f to your computer and use it in GitHub Desktop.
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.
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