Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda