SolidJSS
SolidJSโ€ข3y agoโ€ข
24 replies
akerbeltz

CreateLocalStorage hook problem with reactivity

I'm trying to make a custom hook that exposes a signal and uses the LocalStore of the browser.

import { Signal, createSignal } from "solid-js";

function createStoredSignal<T>(key: string, defaultValue: T, storage = localStorage): Signal<T> {
  const initialValue = storage.getItem(key)
    ? (JSON.parse(storage.getItem(key)) as T)
    : 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];
}
export default createStoredSignal;

the problem is this don't seem to work with reactivity.
Was this page helpful?