Skip to content

Instantly share code, notes, and snippets.

@unlocomqx
Created November 9, 2025 10:37
Show Gist options
  • Select an option

  • Save unlocomqx/1bd052bebf48543debb7b52a54f0f05b to your computer and use it in GitHub Desktop.

Select an option

Save unlocomqx/1bd052bebf48543debb7b52a54f0f05b to your computer and use it in GitHub Desktop.
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