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

107
Visualizações
ReactJS localstorage.getItem is not working

i have a problem with the localstorage.getItem, the setItem function is working fine and the data is stored correctly but when i refresh the page the data is gone. Here is my codes

  useEffect(()=>{
localStorage.setItem(local_Storage_key, JSON.stringify(contacts));
}, [contacts]);

 useEffect(()=>{
    const storage = JSON.parse(localStorage.getItem(local_Storage_key));
    if (storage) {setContacts(storage);}
    }, []);

picture of the localstorage before i refresh the page

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

I think that's because your below code is executing after component has been mounted.

useEffect(()=>{
    localStorage.setItem(local_Storage_key, JSON.stringify(contacts));
}, [contacts]);

And because of this it is setting the initial value of contacts into the localStorage again. To avoid this you can set the initial value of contacts to the value you get from the localStorage

const [contacts,setContacts] = useState(JSON.parse(localStorage.getItem(local_Storage_key)));

useEffect(()=>{
    localStorage.setItem(local_Storage_key, JSON.stringify(contacts));
}, [contacts]);

// remove another useEffect
about 4 years ago · Santiago Gelvez Relatório

0

I suggest you use useLocalStorage

import { useLocalStorage } from 'react-use';

const Demo = () => {
  const [value, setValue, remove] = useLocalStorage('my-key', 'foo');

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue('bar')}>bar</button>
      <button onClick={() => setValue('baz')}>baz</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
};
about 4 years ago · Santiago Gelvez 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