Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
6794 stevensc 1
import { useState, useCallback } from 'react'
2
 
3
const useLocalStorage = ({ stateName, initialValue }) => {
4
  const name = `persist/${stateName}`
5
 
6
  const getFromStorage = (name, defaultValue) => {
7
    try {
8
      const val = JSON.parse(localStorage.getItem(name) + '')
9
      if (val !== null) {
10
        return val
11
      } else {
12
        localStorage.setItem(name, JSON.stringify(defaultValue))
13
      }
14
    } catch {
15
      return defaultValue
16
    }
17
  }
18
 
19
  const [state, setState] = useState(getFromStorage(name, initialValue))
20
 
21
  const setValue = useCallback(
22
    (value) => {
23
      localStorage.setItem(name, JSON.stringify(value))
24
      setState(value)
25
    },
26
    [name]
27
  )
28
 
29
  return [state, setValue]
30
}
31
 
32
export default useLocalStorage