Open History to see the last commit
1import { createEffect, createSignal } from 'solid-js'
2import type { Accessor } from 'solid-js'
3β
4const getItem = (key: string): unknown => {
5 try {
6 const itemValue = localStorage.getItem(key)
7 if (typeof itemValue === 'string') {
8 return JSON.parse(itemValue)
9 }
10 return undefined
11 } catch {
12 return undefined
13 }
14}
15β
16export default function useLocalStorage<T>(
17 key: string,
18 defaultValue: T | undefined,
19): [Accessor<T | undefined>, (newVal: T | ((prevVal: T) => T)) => void] {
20 const [value, setValue] = createSignal<T>()
21β
22 createEffect(() => {
23 const initialValue = getItem(key) as T | undefined
24β
25 if (typeof initialValue === 'undefined' || initialValue === null) {
26 setValue(
27 typeof defaultValue === 'function' ? defaultValue() : defaultValue,
28 )
29 } else {
30 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
31 // @ts-ignore
32 setValue(initialValue)
33 }
34 })
35β
36 const setter = (updater: any) => {
37 setValue((old) => {
38 let newVal = updater
39β
40 if (typeof updater == 'function') {
41 newVal = updater(old)
42 }
43 try {
44 localStorage.setItem(key, JSON.stringify(newVal))
45 } catch {}
46β
47 return newVal
48 })
49 }
50β
51 return [value, setter]
52}