I'm trying to insert an empty array into localStorage if item doesn't exist:
static getLocalActivities(){
var localActivities = localStorage.getItem("Local-Activities");
if (localActivities === undefined){
LocalStorageFunctions.createLocalActivities()
return JSON.parse(localStorage.getItem("Local-Activities"))
}
else{
if (localActivities.length === 0){return localActivities}
else{
// return JSON.parse(localActivities) // fails because not empty arr
return localActivities;
}
}
}
static createLocalActivities(){
return localStorage.setItem('Local-Activities', []); // < this doesnt work
// return localStorage.setItem('Local-Activities', JSON.stringify([])); // < this doesnt work
}
both methods for creating the item always in application chrome tools show:
CodePudding user response:
Problem
- This
var localActivities = localStorage.getItem("Local-Activities");returns'undefined'and notundefined- take notice that the first one is a string. - This if is always false
if (localActivities === undefined){becauselocalActivitiesis'undefined'notundefined - Hence
createLocalActivitiesnever runs
Solution
- Clear the localStorage value from the dev tools
- Use
JSON.stringifyto save values as suggested in the comments

