Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

after refreshing page and adding new values old localstorage values get erased

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
          }
        }
      }

>Solution :

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
          }
        }
      }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading