3

I'm trying to make a custom "hook" for solid-js that will retrieve state from local storage.

import { Accessor, createSignal, Setter } from "solid-js";

export default function createLocalStorageSignal<T extends string>(key: string): [get: Accessor<T>, set: Setter<T>] {
    const storage = window.localStorage;
    const initialValue: T = JSON.parse(storage.getItem(key) ?? '{}').value;

    const [value,setValue] = createSignal<T>(initialValue);

    const newSetValue: Setter<T> = (newValue) => {
            setValue(newValue);
            storage.setItem(key, JSON.stringify({value: newValue}));

            return newValue;
        }

    return [
        value,
        newSetValue
    ]
}

However I get the type error

Type '(newValue: any) => void' is not assignable to type 'Setter<T>'

Why can't newValue's type be inferred? and if it can't be inferred what do I set it to?

EDIT: Setter<T>'s full type is

type Setter<T> = undefined extends T ? 
    <U extends T>
        (v?: (U extends Function ? never : U) |
        ((prev?: T | undefined) => U) | undefined) => U : 
    <U extends T>
        (v: (U extends Function ? never : U) |
        ((prev: T) => U)) => U

I don't exactly understand the purpose of the U type and how it works. I think the problem relates to the fact that newValue could potentially be a function but the T type could also be a function type or something...

snnsnn
  • 10,486
  • 4
  • 39
  • 44
Zachiah
  • 1,750
  • 7
  • 28
  • 2
    The NPM package [@solid-primitives/storage](https://www.npmjs.com/package/@solid-primitives/storage) may be of use! – Alan H. Dec 12 '22 at 17:39

3 Answers3

4

Building on trusktr's answer, simplifying the setValue wrapper function and adding parameters for defaultValue and storage (so you can use sessionStorage if you want):

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];
}

skot
  • 428
  • 5
  • 10
3

Here's one way to do it:

import { Accessor, createSignal, Setter } from "solid-js";

export default function createLocalStorageSignal<T extends object>(
  key: string
): T extends (...args: never) => unknown ? unknown : [get: Accessor<T>, set: Setter<T>];
export default function createLocalStorageSignal<T extends object>(key: string): [Accessor<T>, Setter<T>] {
  const storage = window.localStorage;
  const initialValue: T = JSON.parse(storage.getItem(key) ?? "{}").value;

  const [value, setValue] = createSignal<T>(initialValue);

  const newSetValue = (newValue: T | ((v: T) => T)): T => {
    const _val: T = typeof newValue === 'function' ? newValue(value()) : newValue

    setValue(_val as any);
    storage.setItem(key, JSON.stringify({ value: _val }));

    return _val;
  };

  return [value, newSetValue as Setter<T>];
}

type MyObjectType = {
  foo: string
  bar: number
}

const [get, set] = createLocalStorageSignal<MyObjectType>('asdf')

const val = get() // type of val is MyObjectType

set({} as MyObjectType) // ok
set(() => ({} as MyObjectType)) // ok
set((prev: MyObjectType) => ({} as MyObjectType)) // ok

const str: string = val.foo // ok
const num: number = val.bar // ok

const bool: boolean = val.foo // string is not assignable to boolean (as expected)
const sym: symbol = val.bar // number is not assignable to symbol (as expected)


// This is made to have a type error because function values can not be JSON.stringified.
const [get2, set2] = createLocalStorageSignal<() => void>('asdf')

const val2 = get2() // type of val is any, but that's because of the previous error.

TS playground example

trusktr
  • 44,284
  • 53
  • 191
  • 263
3

Unlike React, effects in SolidJS are not scoped to components, they can be used in functions directly.

You can create a signal in your hook, track state value in an effect and update the local storage whenever the effect fires.

The try/catch block is a safety measure in case previously stored value can not be parsed. In that case it will be overwritten with the initial value.

import { createEffect } from 'solid-js';
import { render } from 'solid-js/web';
import { createStore, Store, SetStoreFunction } from 'solid-js/store';

function createLocalStore<T>(initState: T): [Store<T>, SetStoreFunction<T>] {
  const [state, setState] = createStore(initState);
  if (localStorage.mystore) {
    try {
      setState(JSON.parse(localStorage.mystore));
    } catch (error) {
      setState(() => initialState);
    }
  }
  createEffect(() => {
    localStorage.mystore = JSON.stringify(state);
  });
  return [state, setState];
}


const App = () => {
  const [store, setStore] = createLocalStore({ count: 0 });

  const handleClick = () => setStore('count', c => c + 1);

  return (
    <div onclick={handleClick}>count: {store.count}</div>
  );
};

render(App, document.querySelector('#app'));
snnsnn
  • 10,486
  • 4
  • 39
  • 44