epicweb-dev / react-hooks

Learn React Hooks! 🎣 ⚛
https://hooks.epicreact.dev
Other
2.78k stars 1.91k forks source link

local-state-key-change example has a syntax error if there's a name in local storage already #217

Closed jaharnum closed 1 year ago

jaharnum commented 1 year ago

If I open http://localhost:3000/isolated/examples/local-state-key-change.js with a name already stored in local storage state from testing exercise 2, the page will not load and gives a few error messages.

Uncaught SyntaxError: Unexpected token 'e', "test" is not valid JSON
    at parse (<anonymous>)
    at utils.js:18:1
    at mountState (react-dom.development.js:16986:1)
    at Object.useState (react-dom.development.js:17699:1)
    at Object.useState (react.development.js:1622:1)
    at useLocalStorageState (utils.js:15:1)
    at Greeting (local-state-key-change.js:10:1)
    at renderWithHooks (react-dom.development.js:16305:1)
    at mountIndeterminateComponent (react-dom.development.js:20074:1)
    at beginWork (react-dom.development.js:21587:1)
The above error occurred in the <Greeting> component:

    at Greeting (http://localhost:3000/static/js/src_examples_local-state-key-change_js.chunk.js:32:3)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

It works fine when I remove the name beforehand.

I am guessing this is due to the fact that I haven't completed the extra credit that turns the input name into JSON before storing it, but the useLocalStorageState in utils expects it to be in that format.

This is handled in 02.extra-4.js with a try/catch that simply removes the offending item, but not in utils.js, so it should be an easy fix :)

kentcdodds commented 1 year ago

Thanks for this! Would you be willing to make a pull request for this fix?