src/shared/hooks/useSessionStorage.ts   A
last analyzed

Complexity

Total Complexity 4
Complexity/F 0

Size

Lines of Code 26
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 20
mnd 4
bc 4
fnc 0
dl 0
loc 26
rs 10
bpm 0
cpm 0
noi 1
c 0
b 0
f 0
1
import { useState } from 'react'
2
3
export const useSessionStorage = (key: string, initialValue: string) => {
4
  const [storedValue, setStoredValue] = useState(() => {
5
    try {
6
      const item = window.sessionStorage.getItem(key)
7
      return item ? JSON.parse(item) : initialValue
8
    } catch (error) {
9
      console.error(error)
10
      return initialValue
11
    }
12
  })
13
14
  const setValue = (value: any) => {
0 ignored issues
show
introduced by
Unexpected any. Specify a different type.
Loading history...
15
    try {
16
      const valueToStore =
17
        value instanceof Function ? value(storedValue) : value
18
      setStoredValue(valueToStore)
19
      window.sessionStorage.setItem(key, JSON.stringify(valueToStore))
20
    } catch (error) {
21
      console.log(error)
22
    }
23
  }
24
  return [storedValue, setValue]
25
}
26