Home > database >  after refreshing page and adding new values old localstorage values get erased
after refreshing page and adding new values old localstorage values get erased

Time:02-11

My local storage works correctly but the only issue I've ran it to is when I try adding a new value after a page refresh the previously stored values get erased. I think it may be because I'm using the same key.

I tried this localStorage.setItem("name_" new Date().getTime(), JSON.stringify(favs))

but it didn't help.

This is my function to add a value and store it in to localstorage

value is a string from an array

const favs [];
 
   function addValue(e) {
        if (e.target.value !== "") {
          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
            console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }

CodePudding user response:

Every time you reload the page you're re-initializing favs instead of loading it from the localStorage so it's overwriting it when you save the first value. What you need to do is get the value from the localStorage first and then push the new value. You can do this on page load or when you first try to push the value to localStorage, like so:

let favs = [];
 
   function addValue(e) {
        if (e.target.value !== "") {
          if (favs === []) {
            favs = JSON.parse(localStorage.getItem("name"));
          }

          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
            console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }
  • Related