2

I'm making a HTML5 idle game to practice JavaScript. I'm trying to save information in localStorage, and based on examples and tutorials I've found I'm doing everything right. However, it is not working. What am I doing wrong?

My code:

let gameData = {
    money: 0
}
document.body.onkeyup = function(e) {
    if (e.key == " " ||
        e.code == "Space" ||      
        e.keyCode == 32      
    ) {
        money++;
        refresh();
    }
}
window.onload = (function() {
    load();
    refresh();
});
function refresh() {
    gameData = {
        money: money
    }
    upd(info);
}
window.onbeforeunload = save;
function save() {
    localStorage.setItem("lastGameState", JSON.stringify(gameData))
}
function load() {
    if (localStorage.length > 0) {
        let lastLoad = JSON.parse(localStorage.getItem("lastGameState"));
        gameData = {
            money: lastLoad.money
        }
    }
}

I want to be able to add as many variables as I want (without exceeding localStorage limit) to the variable gameData, when the page closes it will save, and when the page loads it will load, or, if no load found, set to 0. The upd() function just loads the variables onto the screen.

EDIT: I got it to work, it turns out the problem I had was unrelated to localStorage, there was an error in the refresh function. Thank you

  • 5
    This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Apr 21 '23 at 12:21
  • 1
    Also try to execute your code bit by bit rather than all at once. At first glance I can spot that in your onkeyup you do money++ but money wasn't defined. Did you mean gameData.money++ ? Same in refresh(). What did you intend to do with gameData = { money: money } ? – Emilien Apr 21 '23 at 12:27
  • Also if you want to practice using localStorage I suggest you start with something simple like storing a string, and then retrieving it and logging it in the console. Once this works, do the same with an object (with stringify/parse) and then you can carry one with your game. – Emilien Apr 21 '23 at 12:32

0 Answers0