Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  146] [ 5]  / answers: 1 / hits: 20999  / 5 Years ago, fri, february 15, 2019, 12:00:00

The error was happening here:



let moonPortfolio;
...
moonPortfolio = JSON.parse(localStorage.getItem('moonPortfolio'));


I found this answer which makes sense, however I'm still getting that error after this refactor:




As the error says, localStorage.getItem() can return either a string or null. JSON.parse() requires a string, so you should test the result of localStorage.getItem() before you try to use it.




if (portfolio.length === 0) {
const storedPortfolio = localStorage.getItem('moonPortfolio');

if (typeof storedPortfolio === 'string') {
moonPortfolio = JSON.parse(localStorage.getItem('moonPortfolio'));
}
else {
moonPortfolio = [];
}

if (moonPortfolio) {
const savedPortfolio = Object.values(moonPortfolio);
this.props.fetchAllAssets();
// this.props.addCoins(savedPortfolio);
}
}


enter



I first set the results of localStorage moonPortfolio to a var, then check if the var is typeof string. Yet still getting the typescript error?



Any thoughts or direction here?


More From » typescript

 Answers
27

The compiler doesn't know too much about the inner workings of localStorage.getItem and doesn't make the assumption that the return value will be the same from one call of getItem to the next. So it just tells you that it can't be certain that on the second call to getItem the result isn't null.



Try simply passing in the variable you've already created instead of reading from localStorage again:



if (typeof storedPortfolio === 'string') {
moonPortfolio = JSON.parse(storedPortfolio);
}

[#52586] Tuesday, February 12, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;