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

145
Views
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 answers
Answer question

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 Report

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 Report

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 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!