localStorage .parse .stringify

Viewed 442

I need help with pushing 2 data values into localStorage. I know a little about the stringify and parse methods but cant grasp how to implement them.The 2 data values are from "Scores" and "saveName"(a username that is put into an input box).

var Score = (answeredCorrect * 20) + (timeleft);
var saveName = document.querySelector("#saveName");
function Storage() {
  localStorage.setItem("User", JSON.stringify(saveName.value));
  localStorage.setItem("Scores", JSON.stringify(Score));
  var GetStorage = localStorage.getItem("User");
  var GetStorage2 = localStorage.getItem("Scores");
  return {
    first:console.log("GetStorage: "+ GetStorage + GetStorage2),
    second:GetStorage,
    third:GetStorage2,
  };
};
var values = Storage();
var first = values.first;
var second = values.second;
var third = values.third;
1 Answers

As mentioned in the comments you need to parse it once retrieved from storage with JSON.parse, also naming Storage should be avoided.

Since your making a wrapper for localstorage, it could be done like this:

const Store = {
  set: (key, value) => localStorage[key] = JSON.stringify(value),
  get: key => JSON.parse(localStorage[key])
}

Then you can simply call it like the following, with a set and get methods:

//
Store.set('Score', Score)
Score = Store.get('Score')

//
Store.set('User', saveName.value)
saveName = Store.get('User')

Though you only need to get() on page load as you already have the value in Score/saveName etc.

Related