Frames

Untitled

0
1import {useState, useEffect} from 'react'
2
3const useLocalStorage = (key, {updateFrequency = 1000} = {}) => {
4 const [value, setValue] = useState()
5
6 const writeToLocalStorage = newValue => {
7 if (newValue !== undefined) {
8 localStorage.setItem(key, newValue)
9 }
10 else {
11 localStorage.removeItem(key)
12 }
13 setValue(newValue)
14 }
15
16 useEffect(() => {
17 const readFromLocalStorage = () => {
18 const oldValue = value
19 const newValue = localStorage.getItem(key)
20 if (newValue !== oldValue) {
21 setValue(newValue)
22 }
23 }
24
25 let readLocalStorageIntervalId
26 if (window.localStorage) {
27 readFromLocalStorage()
28 readLocalStorageIntervalId = setInterval(
29 readFromLocalStorage,
30 updateFrequency
31 )
32 }
33 return () => {
34 if (window.localStorage) {
35 clearInterval(readLocalStorageIntervalId)
36 }
37 }
38 }, [key, value, updateFrequency])
39
40 return [value, writeToLocalStorage]
41}
42
43const useLocalStorageNoSync = key => {
44 const [value, setValue] = useState()
45
46 const readFromLocalStorage = () => {
47 const oldValue = value
48 const newValue = localStorage.getItem(key)
49 if (newValue !== oldValue) {
50 setValue(newValue)
51 }
52 return newValue
53 }
54
55 const writeToLocalStorage = newValue => {
56 if (newValue !== undefined) {
57 localStorage.setItem(key, newValue)
58 }
59 else {
60 localStorage.removeItem(key)
61 }
62 setValue(newValue)
63 }
64
65 return [readFromLocalStorage, writeToLocalStorage]
66}
67
68export default useLocalStorage
69
70export {useLocalStorageNoSync}
71