Skip to content

Instantly share code, notes, and snippets.

@arxpoetica
Created October 19, 2024 15:43
Show Gist options
  • Save arxpoetica/db115298277830209da72e04112b421d to your computer and use it in GitHub Desktop.
Save arxpoetica/db115298277830209da72e04112b421d to your computer and use it in GitHub Desktop.
Naive Storage Sync
import { getStorage, storageSync } from '$shared/state-utils.svelte';
const SYNC_KEY = 'some_synced_var';
class SomeSvelteClass {
some_synced_var = $state(getStorage(SYNC_KEY) || 'foo');
constructor() {
storageSync(SYNC_KEY, () => this.some_synced_var);
}
}
import { browser } from '$app/environment';
import { uneval } from 'devalue';
type LocalWatchType = 'localStorage' | 'sessionStorage';
type Getter = () => any;
export const getStorage = (key: string, type: LocalWatchType = 'localStorage') => {
if (!browser) return;
const value = window[type][key];
return value ? (0, eval)('(' + value + ')') : undefined;
};
export const storageSync = (key: string, getter: Getter, type: LocalWatchType = 'localStorage') => {
if (!browser) return;
$effect(() => {
const value = getter();
if (value === undefined) {
window[type].removeItem(key);
} else {
window[type][key] = uneval(value);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment