Created
January 20, 2026 13:25
-
-
Save shiftgeist/c6a7eac89f2f74e58c6a03b7fcc01e9f to your computer and use it in GitHub Desktop.
svelte localStorage state
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 { browser } from "$app/environment"; | |
| export class LocalStore<T> { | |
| value = $state<T>() as T; | |
| key = ""; | |
| constructor(key: string, value: T) { | |
| this.key = key; | |
| this.value = value; | |
| if (browser) { | |
| const item = localStorage.getItem(key); | |
| if (item) this.value = this.deserialize(item); | |
| } | |
| $effect.root(() => { | |
| $effect(() => { | |
| localStorage.setItem(this.key, this.serialize(this.value)); | |
| }); | |
| }); | |
| } | |
| serialize(value: T): string { | |
| return JSON.stringify(value); | |
| } | |
| deserialize(item: string): T { | |
| return JSON.parse(item); | |
| } | |
| } | |
| export function localState<T>(key: string, value: T) { | |
| return new LocalStore(key, value); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment