Skip to content

Commit 624bdb4

Browse files
jaharnumJamie Harnum
and
Jamie Harnum
authored
Use local storage state fix (#218)
* Completed first two exercises * Revert "Completed first two exercises" This reverts commit cf4d7a8. * Replace utils useLocalStorageState with the one from 2.extra4.js --------- Co-authored-by: Jamie Harnum <[email protected]>
1 parent e476a18 commit 624bdb4

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

src/utils.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,27 @@ import * as React from 'react'
1010
function useLocalStorageState(
1111
key,
1212
defaultValue = '',
13+
// the = {} fixes the error we would get from destructuring when no argument was passed
14+
// Check https://jacobparis.com/blog/destructure-arguments for a detailed explanation
1315
{serialize = JSON.stringify, deserialize = JSON.parse} = {},
1416
) {
1517
const [state, setState] = React.useState(() => {
1618
const valueInLocalStorage = window.localStorage.getItem(key)
1719
if (valueInLocalStorage) {
18-
return deserialize(valueInLocalStorage)
20+
// the try/catch is here in case the localStorage value was set before
21+
// we had the serialization in place (like we do in previous extra credits)
22+
try {
23+
return deserialize(valueInLocalStorage)
24+
} catch (error) {
25+
window.localStorage.removeItem(key)
26+
}
1927
}
2028
return typeof defaultValue === 'function' ? defaultValue() : defaultValue
2129
})
2230

2331
const prevKeyRef = React.useRef(key)
2432

33+
// Check the example at src/examples/local-state-key-change.js to visualize a key change
2534
React.useEffect(() => {
2635
const prevKey = prevKeyRef.current
2736
if (prevKey !== key) {

0 commit comments

Comments
 (0)