Created
November 9, 2025 10:37
-
-
Save unlocomqx/1bd052bebf48543debb7b52a54f0f05b to your computer and use it in GitHub Desktop.
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 cookies from 'browser-cookies'; | |
| import { browser } from '$app/environment'; | |
| let { erase, get, set } = cookies; | |
| export class LocalStore<T> { | |
| value = $state<T>() as T; | |
| key = ''; | |
| constructor(key: string, default: T) { | |
| this.key = key; | |
| this.value = default; | |
| if (browser) { | |
| const item = get(key); | |
| if (item) this.value = this.deserialize(item); | |
| } | |
| $effect.root(() => { | |
| $effect(() => { | |
| if (this.value) { | |
| set(this.key, this.serialize(this.value)); | |
| } else { | |
| erase(this.key); | |
| } | |
| }); | |
| }); | |
| } | |
| serialize(value: T): string { | |
| return JSON.stringify(value); | |
| } | |
| deserialize(item: string): T { | |
| return JSON.parse(item); | |
| } | |
| } | |
| // example | |
| let theme = new LocalStore<string>('theme', 'light'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment