summaryrefslogtreecommitdiff
path: root/util/persistant-state.ts
blob: 2907e702cae4e6cedbbb293b02e9478d2e4f6147 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { useState, useEffect } from 'react'

export function usePersistantState<V>(
  storageKey: string,
  defaultValue: V,
  options: {
    storage?: Storage
  } = {},
): [V, (v: V | ((v: V) => V)) => void] {
  const storage = getStorage<V | undefined>(storageKey, options.storage ?? localStorage)

  const storageValue = storage.get()
  const calculatedDefaultValue = storageValue !== undefined ? storageValue : defaultValue
  const calculatedDefaultValueObject =
    storageValue != null &&
    typeof storageValue === 'object' &&
    Array.isArray(storageValue) === false
      ? { ...defaultValue, ...storageValue }
      : calculatedDefaultValue
  if (calculatedDefaultValueObject !== storageValue) {
    storage.update(calculatedDefaultValueObject)
  }
  const [value, setValue] = useState<V>(calculatedDefaultValueObject)

  // change state gracefully when changing the storageKey
  useEffect(() => {
    if (value !== calculatedDefaultValueObject) {
      setValue(calculatedDefaultValueObject)
    }
  }, [storageKey])
  const set = (newValueOrFn: V | ((v: V) => V)) => {
    if (newValueOrFn instanceof Function) {
      setValue((oldValue) => {
        const newValue = newValueOrFn(oldValue)
        storage.update(newValue)
        return newValue
      })
      return
    }
    setValue(newValueOrFn)
    storage.update(newValueOrFn)
  }

  return [value, set]
}

export function getStorage<T>(key: string, storage: Storage) {
  return {
    get(): T | undefined {
      const value = storage.getItem(key)
      if (value && value !== 'undefined') {
        return JSON.parse(value)
      }

      return undefined
    },
    update(updatedState: T) {
      storage.setItem(key, JSON.stringify(updatedState))
    },
    remove() {
      storage.removeItem(key)
    },
  }
}