Home > OS >  JSON.parse an Undefined object from Local Storage
JSON.parse an Undefined object from Local Storage

Time:10-01

I am having a LocalStorage item which I am parsing into a variable like this:

let resp = JSON.parse(localStorage.getItem('someKey'));

The thing is sometimes, the localStorage may not have the value and it may return an Undefined object to parse which is resulting in following error:

SyntaxError: Unexpected token U in JSON at position 0

I have tried this:

let resp = localStorage.getItem('someKey') ? JSON.parse(localStorage.getItem('someKey')) : null;

But I believe this is not very optimal way of handling this, any suggestions are welcome

CodePudding user response:

your solution is just fine, if you want it to be shorter, you could try this

let resp = JSON.parse(localStorage.getItem('someKey') || null)

Here is how it works:

  1. localStorage.getItem('someKey') || null will evaluate the left side of the code first, if localStorage.getItem('someKey') returns undefined or '' empty string, it will return the right side code which is null

  2. Then, JSON.parse(null) will return null instead of error

CodePudding user response:

You could try something like this:

let resp = null;
const storedResp = localStorage.getItem('someKey');
if (storedResp) {
  try {
    resp = JSON.parse(storedResp);
  } catch (e) {}
}

This shouldn't generate any errors since you're only parsing it to JSON if it exists, and then catching any errors if JSON parsing fails. You're left with resp being equal to null or the stored data as JSON, with no errors in any case.

As others have said, your current solution is fine, but there are two potential issues with it as written:

  • You access the item in localStorage twice, which may be unnecessarily slow if it is a large object.
  • Many companies prefer (or require) that you wrap lines at 80 characters and your current solution is 96 characters long.
  • Related