Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Last active July 30, 2022 14:33
Show Gist options
  • Save dr-skot/ef6a646eb988808f91e1a4abe8088934 to your computer and use it in GitHub Desktop.
Save dr-skot/ef6a646eb988808f91e1a4abe8088934 to your computer and use it in GitHub Desktop.
A SolidJS signal that maintains persistence in local or session storage.
import { createSignal, Signal } from "solid-js";
export function createStoredSignal<T>(key: string, defaultValue: T, storage = localStorage): Signal<T> {
const initialValue = tryToParse(storage.getItem(key), defaultValue);
const [value, setValue] = createSignal<T>(initialValue);
const setValueAndStore = ((arg) => {
const v = setValue(arg);
storage.setItem(key, JSON.stringify(v));
return v;
}) as typeof setValue;
return [value, setValueAndStore];
}
function tryToParse<T>(json: string | null | undefined, fallback: T): T {
if (!json) return fallback;
try {
return JSON.parse(json) as T;
} catch {
return fallback;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment