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')
CodePudding user response:
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({});
CodePudding user response:
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
CodePudding user response:
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.
CodePudding user response:
The other answers cover the reasons of the Exception, this is just the simplest fix:
console.log(carinfo?.brand);
CodePudding user response:
carinfo
is undefined during first render. Try this:
const [carinfo, setCarInfo] = useState({});
useEffect(() => {
const storedData = JSON.parse(localStorage.getItem('carData'));
setCarInfo(storedData);
console.log(storedData.brand);
}, []);
// FIX 1
useEffect(() => {
if (carinfo && carinfo.brand) {
console.log(carinfo.brand);
}
}, [carinfo]);
// FIX 2
console.log(carinfo?.brand);