Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error when persisting the value 'undefined': JSON.parse throws an exception #99

Open
pistillo opened this issue Oct 30, 2024 · 0 comments

Comments

@pistillo
Copy link

When the value 'undefined' is persisted accidentally in storage, attempting to retrieve and parse it using JSON.parse throws an exception. This happens because JSON.parse('undefined') is not valid JSON, resulting in a runtime error.

storage-utils.ts

// Example retrieval code
const item = localStorage.getItem('key');
return item ? JSON.parse(item) : null; // JSON.parse(item) fails if item is 'undefined'

A potential fix could include checking explicitly for 'undefined' as a string, to avoid parsing errors:

return item && item !== 'undefined' ? JSON.parse(item) : null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant