Search code examples
javascriptlocal-storagepage-refresh

How to save in localStorage that refreshing browser do not change the value (JavaScript)?


I have a counter of clicks. Every click increase value. I'd like to save to in local storage, that refreshing page keeps the value. Now it saves the value in local storage, but not keep it if I refresh the browser. What should I change in my code to make it work properly?

let countedClicks = 0;
    
const countingClicks = () => {
  countedClicks += 1;
  localStorage.setItem("btnClicksSaved", countedClicks);
  let savedClicks = localStorage.getItem("btnClicksSaved");
  clicks.innerHTML = `${savedClicks} times`;
  console.log(countedClicks + "counted");
  console.log(savedClicks + "local storage");

  if (savedClicks > 5) {
    resetBtn.style.display = "flex";
  } else {
    resetBtn.style.display = "none";
  }
};

Solution

  • You should get data first otherwise it will always start with 0.

    let countedClicks = parseInt(localStorage.getItem("btnClicksSaved") ?? '0');
        
    const countingClicks = () => {
      countedClicks += 1;
      localStorage.setItem("btnClicksSaved", countedClicks);
      let savedClicks = localStorage.getItem("btnClicksSaved");
      clicks.innerHTML = `${savedClicks} times`;
      console.log(countedClicks + "counted");
      console.log(savedClicks + "local storage");
    
      if (savedClicks > 5) {
        resetBtn.style.display = "flex";
      } else {
        resetBtn.style.display = "none";
      }
    };