Created
October 19, 2024 15:43
-
-
Save arxpoetica/db115298277830209da72e04112b421d to your computer and use it in GitHub Desktop.
Naive Storage Sync
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 { 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); | |
} | |
} |
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'; | |
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