最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot call `JSON.parse` with `localStorage.getItem(...)` - Stack Overflow

programmeradmin4浏览0评论

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 that JSON.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
 |  Show 2 more ments

2 Answers 2

Reset to default 12

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.

Prefer using 'null' than '{}' as it parses to empty object

JSON.parse(localStorage.getItem("key") || 'null') // null

JSON.parse(localStorage.getItem("key") || '{}') // {} - empty object 
发布评论

评论列表(0)

  1. 暂无评论