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){
becauselocalActivities
is'undefined'
notundefined
- Hence
createLocalActivities
never runs
Solution
- Clear the localStorage value from the dev tools
- Use
JSON.stringify
to save values as suggested in the comments