Search code examples
javascriptsavelocal-storageloading

Saving game in local storage results in [object Object] and undefined


model is an object that contains every single variable in my code in the form of arrays and objects. I want to save a snapshot of the values within whenever I use the saveGame function, and then redefine it to that snapshot whenever I use the loadGame function. However, when I use loadGame(), it returns [object Object], and then every single piece of information within becomes undefined. What gives?

function saveGame() {
    localStorage.setItem('model', model);
}
function loadGame() {
    model = localStorage.getItem('model');
    updateView();
}

Solution

  • According to MDN web docs, keys and values stored in localStorage are always in UTF-16 DOMString format.

    Therefore you can't store an object inside of a localStorage. Since it only accepts strings. The [object Object] you mentioned is a string representation of an object which it automatically creates using the default Object.toString() method.

    To convert an object into a string representation and preserve the variables. You could serialize the object into a JSON string using JSON.stringify(). And later deserialize it using JSON.parse() to convert it back into an object.

    function saveGame() {
        localStorage.setItem('model', JSON.stringify(model));
    }
    function loadGame() {
        model = JSON.parse(localStorage.getItem('model'));
        updateView();
    }