skip to Main Content

to save numbers and booleans I use array destructuring. I simply save by
localStorage.save=JSON.stringify([stat1, stat2, stat3]);
then I load by
[stat1, stat2, stat3] = JSON.parse(localStorage.save);
I just want to know if this is bad, and I should stop or if it is okay.
by the way strings aren’t included in this method unless you do ‘"’+stringvar+’"’ in the save code which is the only thing i noticed

2

Answers


  1. Saving data to the local storage is fine (but keep in mind most browsers have a quota, but a few numbers certainly won’t hit that limit) but your localStorage.save = ... doesn’t make any sense and doesn’t save anything to the local storage. It just sets a custom property of the localStorage object. This may work as long as you don’t reload your site (as everything is kept in memory). But once you reload your site, your data is gone.

    The correct way would be

    localStorage.setItem("gameStats", JSON.stringify([stat1, stat2, stat3]))
    

    and

    let [stat1, stat2, stat3] = JSON.parse(localStorage.getItem("gameStats"));
    
    Login or Signup to reply.
  2. Saving to localStorage is totally ok, the only problem you should be more descriptive with your naming, because there’s nothing deducible if one looks at your stored data.
    Also it’s recommended to use localStorage::setItem() instead of assigning properties to localStorage itself.
    Since you serialize the data with JSON my guess strings will be serialized just ok as well as even objects.
    So I propose:

    // saving (you will save a nice object with descriptive object property names
    // 'gameData' - this is extendable with other data beyond stats
    localStorage.setItem('gameData', JSON.stringify({stat1, stat2, stat3}); 
    
    // restoring
    const {stat1, stat2, stat3} = JSON.parse(localStorage.getItem('gameData'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search