Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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

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
          }
        }
      }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
          }
        }
      }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!