forked from epicweb-dev/react-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02.extra-4.js
65 lines (55 loc) · 1.85 KB
/
02.extra-4.js
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
65
// useEffect: persistent state
// 💯 flexible localStorage hook
// http://localhost:3000/isolated/final/02.extra-4.js
import * as React from 'react'
function useLocalStorageState(
key,
defaultValue = '',
// the = {} fixes the error we would get from destructuring when no argument was passed
// Check https://jacobparis.com/blog/destructure-arguments for a detailed explanation
{serialize = JSON.stringify, deserialize = JSON.parse} = {},
) {
const [state, setState] = React.useState(() => {
const valueInLocalStorage = window.localStorage.getItem(key)
if (valueInLocalStorage) {
// the try/catch is here in case the localStorage value was set before
// we had the serialization in place (like we do in previous extra credits)
try {
return deserialize(valueInLocalStorage)
} catch (error) {
window.localStorage.removeItem(key)
}
}
return typeof defaultValue === 'function' ? defaultValue() : defaultValue
})
const prevKeyRef = React.useRef(key)
// Check the example at src/examples/local-state-key-change.js to visualize a key change
React.useEffect(() => {
const prevKey = prevKeyRef.current
if (prevKey !== key) {
window.localStorage.removeItem(prevKey)
}
prevKeyRef.current = key
window.localStorage.setItem(key, serialize(state))
}, [key, state, serialize])
return [state, setState]
}
function Greeting({initialName = ''}) {
const [name, setName] = useLocalStorageState('name', initialName)
function handleChange(event) {
setName(event.target.value)
}
return (
<div>
<form>
<label htmlFor="name">Name: </label>
<input value={name} onChange={handleChange} id="name" />
</form>
{name ? <strong>Hello {name}</strong> : 'Please type your name'}
</div>
)
}
function App() {
return <Greeting />
}
export default App