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

147
Visualizações
React get value of object from localstorge

I get data from localstorage. I used useEffect. But when I want to get a value in object, I got problem.

const [carinfo, setCarInfo] = useState(); 

useEffect(() => { 
  const storedData = JSON.parse(localStorage.getItem("carData"));
  setCarInfo(storedData); 
  console.log(storedData.brand); 
}, []);

console.log(carinfo.brand);

console.log(storedData.brand) is working.

No console.log(carinfo.brand) is not working

I have this error

Uncaught TypeError: Cannot read properties of undefined (reading 'brand')

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I suspect you get the error because the effect hasn't happened yet. The first time your component renders, carinfo is undefined.

You can set an initial value to state to get around this:

const [carinfo, setCarInfo] = useState({}); 
about 4 years ago · Juan Pablo Isaza Relatório

0

Your console.log(carinfo.brand) is getting executed before the useEffect. That means you're trying to access the value of carinfo before setting it.
Sol 1: Put the console.log(carinfo.brand) inside useEffect

Sol 2: If you need the carinfo outside useEffect, write it inside a function and call that function after setting the carinfo value

about 4 years ago · Juan Pablo Isaza Relatório

0

On your initial render, the value of carinfo will match what you call useState with.

useState() is the equivalent of useState(undefined). undefined is a value without a brand property.

useEffect will fire and then update the state with whatever value you have in localStorage, given that it matches your expected data structure (you may want to consider creating a safer way get to localStorage.

Nevertheless,only after the initial render is the state set, and then you may have the expected value in carinfo.

You can use optional chaining to protect yourself, console.log(carinfo?.brand) or some other way to handle the undefined case.

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