Skip to content

Instantly share code, notes, and snippets.

@kevinsschmidt
Last active April 8, 2024 06:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kevinsschmidt/718a89d47f88f4a4aaa072bca3dd0c01 to your computer and use it in GitHub Desktop.
Save kevinsschmidt/718a89d47f88f4a4aaa072bca3dd0c01 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