Question

This is a follow-up question to this

I started using the localStorage function, and am unsure whether or not its working as intended.

I want to overwrite a boolean in my JSON file.

Player hits an exit in a stage, then it triggers the load of the next stage, but I also want it to save the fact that the stage was completed.

Here is my JSON array, defining that all dungeons are incomplete by default:

var dungeon_prog = {
"dungeon0_prog" : {
    "complete" : true
},
"dungeon1_prog" : {
    "complete" : false
},
"dungeon2_prog" : {
    "complete" : false
}
};

Then I set it to local storage:

localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog));
var dungeon_prog_obj = JSON.parse(localStorage.dungeon_prog);

I want it to override dungeon1_prog "complete" false to true when player hits the exit in dungeon 1.

How would I do this? And are the default "false" statements actually being saved in localStorage? Thanks.

Was it helpful?

Solution

The dungeon_prog_obj now holds your JSON object. To answer your last question, yes - localStorage saves the entire JSON string, thus it also saves the boolean values.

To overwrite it you just have to set the boolean value and them save again to the same localStorage item:

dungeon_prog_obj.dungeon1_prog.complete = true;
localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog_obj));

Edit:

Update in order to answer questions in the comment, per request.

I am not 100% sure that this is the issue, but you are saying that on page refresh the true value does not persist. The only plausible explanation is that on every page load you are overwriting the JSON with the initial one using localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog));, where dungeon_prog is the initial JSON specified in your question.

Instead of doing this, you should check on load if you have the item in localStorage. You can do this in the following way:

// Check for object in localStorage
var dungeon_prog = JSON.parse(localStorage.dungeon_prog);

// If it does not exist, initialize it and save it
if (dungeon_prog != null) {
    dungeonProg = {
        "dungeon0_prog" : {
            "complete" : true
    },
    "dungeon1_prog" : {
        "complete" : false
    },
    "dungeon2_prog" : {
        "complete" : false
   }
   };

   localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top