'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')
Solution 1:[1]
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({});
Solution 2:[2]
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
Solution 3:[3]
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.
Solution 4:[4]
The other answers cover the reasons of the Exception, this is just the simplest fix:
console.log(carinfo?.brand);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gøran Cantona |
Solution 2 | Pavan Aditya M S |
Solution 3 | wlh |
Solution 4 | Cesare Polonara |