All files / Bandstand/src/components useStoredState.ts

89.47% Statements 17/19
50% Branches 3/6
100% Functions 2/2
89.47% Lines 17/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x             1x 51x 51x 20x 20x 20x 20x     51x 51x 5x 5x 5x 5x     5x 51x 51x  
'use client'
 
import {useEffect, useState} from 'react'
 
/**
 * useState that remembers its value on this device. Storage can be missing or
 * throw (private mode, blocked site data), so every access is guarded and the
 * default is used instead.
 */
export function useStoredState<T>(key: string, initial: T) {
  const [value, setValue] = useState<T>(initial)
  useEffect(() => {
    try {
      const raw = window.localStorage.getItem(key)
      if (raw !== null) setValue(JSON.parse(raw) as T)
    } catch {
      // ignore
    }
  }, [key])
  const set = (v: T) => {
    setValue(v)
    try {
      window.localStorage.setItem(key, JSON.stringify(v))
    } catch {
      // ignore
    }
  }
  return [value, set] as const
}