feature/comparison-slider #19
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Reusable persistent storage utility using Svelte 5 runes
|
||||
*
|
||||
* Automatically syncs state with localStorage.
|
||||
*/
|
||||
export function createPersistentStore<T>(key: string, defaultValue: T) {
|
||||
// Initialize from storage or default
|
||||
const loadFromStorage = (): T => {
|
||||
if (typeof window === 'undefined') {
|
||||
return defaultValue;
|
||||
}
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : defaultValue;
|
||||
} catch (error) {
|
||||
console.warn(`[createPersistentStore] Error loading ${key}:`, error);
|
||||
return defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
let value = $state<T>(loadFromStorage());
|
||||
|
||||
// Sync to storage whenever value changes
|
||||
$effect.root(() => {
|
||||
$effect(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch (error) {
|
||||
console.warn(`[createPersistentStore] Error saving ${key}:`, error);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
get value() {
|
||||
return value;
|
||||
},
|
||||
set value(v: T) {
|
||||
value = v;
|
||||
},
|
||||
clear() {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
value = defaultValue;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user