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 inpatible with string [2]
This es 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!
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 inpatible with string [2]
This es 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!
Share Improve this question edited Jan 15, 2024 at 11:11 Vega 28.7k28 gold badges120 silver badges145 bronze badges asked Oct 9, 2018 at 10:29 prokoproko 1952 silver badges13 bronze badges 7-
because
localStorage.getItem("someItem")
can return a null value as well – Daksh M. Commented Oct 9, 2018 at 10:35 - Yes, this is the part I understand. The next step should be something like setting JSON.parse to accept null or undefined maybe? And how? – proko Commented Oct 9, 2018 at 10:38
-
you can do an if statement or something like:
localStorage.getItem("someItem") || {}
– Daksh M. Commented Oct 9, 2018 at 10:39 -
I tried something similar and unfortunately doesn't help. It just adds
object literal is inpatible with string
to the error. Problem is thatJSON.parse
only accepts a string. I guess I could wrap the getItem to a function and make sure it always returns a string but there should be a better solution. – proko Commented Oct 9, 2018 at 10:45 -
localStorage.getItem("someItem") || '{}'
wrap the object in string – Daksh M. Commented Oct 9, 2018 at 11:06
2 Answers
Reset to default 12So, 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.
Prefer using 'null' than '{}' as it parses to empty object
JSON.parse(localStorage.getItem("key") || 'null') // null
JSON.parse(localStorage.getItem("key") || '{}') // {} - empty object