Luca
Luca

Reputation: 358

Saving variables with localStorage does not work correctly

I'm writing a function that saves me some time-persistent variables (I don't have a backend and I don't need it for this exercise), but I notice that the first variable "easy30" saves it in the html and every time I reload the page remains visible, while the second variable "easy60" does not remain. It only saves it the first time and if I reload the page it disappears... why? I basically do the exact same thing for both variables!

 const easy30 = document.getElementById('easy-30');
 const easy60 = document.getElementById('easy-60');

 function saveScoreAndTime(score, time, difficulty) {
   //EASY 30 SECONDS
   var totalScore30 = localStorage.getItem('score30');

   if (
     totalScore30 === null ||
     (+score > +totalScore30 && +time === 30 && difficulty === 'easy')
   ) {
     localStorage.setItem('score30', score);
     let newEasy30Score = localStorage.getItem('score30');
     easy30.textContent = newEasy30Score;
   }

   //EASY 60 SECONDS
   var totalScore60 = localStorage.getItem('score60');

   if (
     totalScore60 === null ||
     (+score > +totalScore60 && +time === 60 && difficulty === 'easy')
   ) {
     localStorage.setItem('score60', score);
     let newEasy60Score = localStorage.getItem('score60');
     easy60.textContent = newEasy60Score;
   }

 }

Upvotes: 0

Views: 180

Answers (1)

Cyrus Zei
Cyrus Zei

Reputation: 2660

So there is a problem with your code.

Why you are getting the HTML node instead of the value is because you are targeting the HTML node and forgot to add the innerHTML

so in your case you should do const easy30 = document.getElementById("easy-30").innerHTML; to get the value of that HTML node

also here is an example to get and set the localstorage

const easy30 = document.getElementById("easy-30");
const easy60 = document.getElementById("easy-60");
console.log("easy30", easy30.innerHTML);
console.log("easy60", easy60.innerHTML);

const init = async () => {
  const score30 = await localStorage.getItem("easy30");
  console.log("score30", score30);
  const score60 = await localStorage.getItem("easy60");
  console.log("score30", score60);
};

init();

const setLocalStorage = async (key) => {
  localStorage.setItem(key, 30);
};
setLocalStorage("score30");
setLocalStorage("score60");

and here is a codesandbox snippet

Upvotes: 1

Related Questions