Last active
July 30, 2022 14:33
-
-
Save dr-skot/ef6a646eb988808f91e1a4abe8088934 to your computer and use it in GitHub Desktop.
A SolidJS signal that maintains persistence in local or session storage.
This file contains 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 { 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