Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jonshipman/9bbde06ddaf8bec8414c9affea3f8cd4 to your computer and use it in GitHub Desktop.
Save jonshipman/9bbde06ddaf8bec8414c9affea3f8cd4 to your computer and use it in GitHub Desktop.
Svelte Persistent Writable
import { writable, type Updater, type Writable } from 'svelte/store';
/**
* Create a writable store that persists to sessionStorage or localStorage.
*
* Usage example:
* export const colorScheme = createPersistentWritable<'system' | 'dark' | 'light'>({ storageId: 'color-scheme', useLocalStorage: true }, 'dark');
*/
export function createPersistentWritable<T>(
{ storageId, useLocalStorage }: { storageId: string; useLocalStorage?: boolean },
initialValue?: T
): Writable<T> {
const storageAvailable =
typeof sessionStorage !== 'undefined' && typeof localStorage !== 'undefined';
if (storageAvailable) {
const jsonString = (useLocalStorage ? localStorage : sessionStorage).getItem(storageId);
if (jsonString) {
initialValue = JSON.parse(jsonString) || initialValue;
}
}
const { subscribe, set, update } = writable<T>(initialValue);
return {
subscribe,
set: function (this: void, value: T): void {
if (storageAvailable) {
typeof value !== 'undefined'
? (useLocalStorage ? localStorage : sessionStorage)?.setItem(
storageId,
JSON.stringify(value)
)
: (useLocalStorage ? localStorage : sessionStorage)?.removeItem(storageId);
}
set(value);
},
update: function (this: void, fn: Updater<T>): void {
update((value) => {
const newValue = fn(value);
if (storageAvailable) {
typeof newValue !== 'undefined'
? (useLocalStorage ? localStorage : sessionStorage)?.setItem(
storageId,
JSON.stringify(newValue)
)
: (useLocalStorage ? localStorage : sessionStorage)?.removeItem(storageId);
}
return newValue;
});
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment