Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call `JSON.parse` with `localStorage.getItem(...)`

Tags:

flowtype

Just added Flow types to a project I'm working on and progressively adding types until I got to this error:

Cannot call JSON.parse with localStorage.getItem(...) bound to text because null or undefined [1] is incompatible with string [2]

This comes from a expression:

const myVar = JSON.parse(localStorage.getItem('itemName'))

I understand why I get this error (except maybe the "bound to text" part), but couldn't find a way around it. I'd appreciate any help here!

like image 631
proko Avatar asked Oct 09 '18 10:10

proko


1 Answers

So, the function localStorage.getItem can return null values and flow wants you to tackle them before parsing it. As JSON.parse only takes a string, you can do the following:

localStorage.getItem("key") || '{}'

So, if it returns null. The empty object string is chosen, which JSON.parse can parse into an empty object.

like image 198
Daksh Miglani Avatar answered Oct 27 '22 00:10

Daksh Miglani