Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda