Handle error when localStorage value is not JSON parseable
See original GitHub issueIf a localStorage value is manually set (not through the hook) and is not valid JSON syntax, this library will throw an error when attempting to parse it:
Uncaught SyntaxError: Unexpected token a in JSON at position 0
Ideally, the hook should handle this error gracefully, in the case that another piece of code overrides the value or it is edited manually through dev tools.
Places to error check:
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:13 (9 by maintainers)
Top Results From Across the Web
JSON.parse throwing error for invalid JSON not handled #98
So if I want to store my data as JSON string in local storage, there is no way to avoid this issue. This...
Read more >JSON.parse an Undefined object from Local Storage
your solution is just fine, if you want it to be shorter, you could try this let resp = JSON.parse(localStorage.getItem('someKey') || null).
Read more >JSON.parse() - JavaScript - MDN Web Docs
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
Read more >How To Fix Unexpected token u in JSON at position 0 - Isotropic
This error is caused when you are attempting to parse a non-existent property. Typically, this is due to a misspelling, or simply referencing ......
Read more >The source code
Omitted if the * error is not module-related or the module cannot be easily identified due to * batched handling. * @param {string}...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’ve encountered this. When you’re not following your good advise on namespacing keys, it’s possible (and potentially likely) that you may be using a key that some other app might also be using. In this case, their data may not be JSON and thus crash.
The obvious solution to this is to use namespaced keys, but having a way to gracefully recover would be nice. Maybe use the default value and do a
console.warn
?I have thought a lot about this. I decided to put everything in place so the library doesn’t throw any errors. The new 5.1.0 release includes everything needed. Hope you like the change. Thanks to everybody who shared your opinion.
I am closing this issue now.