Files
nodarium/app/src/lib/helpers/localState.svelte.ts
Max Richter cfcb447784
All checks were successful
Deploy to GitHub Pages / build_site (push) Successful in 2m48s
feat: update some more components to svelte 5
2025-11-24 21:11:16 +01:00

35 lines
696 B
TypeScript

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);
}