Home > Net >  Why does my local storage item appear to be defined when it isn't?
Why does my local storage item appear to be defined when it isn't?

Time:09-08

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:

enter image description here

CodePudding user response:

Problem

  1. This var localActivities = localStorage.getItem("Local-Activities"); returns 'undefined' and not undefined - take notice that the first one is a string.
  2. This if is always false if (localActivities === undefined){ because localActivities is 'undefined' not undefined
  3. Hence createLocalActivities never runs

Solution

  1. Clear the localStorage value from the dev tools
  2. Use JSON.stringify to save values as suggested in the comments
  • Related