-
-
Save jonshipman/9bbde06ddaf8bec8414c9affea3f8cd4 to your computer and use it in GitHub Desktop.
Svelte Persistent Writable
This file contains 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, 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