In React, you can use useEffect() hook with a dependency on it.
const [data, setData] = useState();
useEffect(() => {
console.log(data.test.test);
}, [data]);
So I would assume that this useEffect is just called when the data is changed. So let´s assume I would make an api call and use setData(response.data).
Then the useEffect() should be triggerd, since the data state is a dependecy.
Then the console.log(data.tes.test) would be working, since I got the right data. However, I get an undefined error, which comes from the fact that useEffect() is also called initially.
How can I avoid this? This is pretty annoying and in my mind not a good design with regard to adding a dependency.
CodePudding user response:
You can make a condition to set the data only when if the data != undefined
. This way, useEffect
is only triggered on data
updates where the data
is defined.
if(response.data != undefined){
setData(() => response.data)
}
CodePudding user response:
The useEffect hook will be callend always at least once, and if has dependencies will be triggered again at any changes detected, you could do a conditional inside if you want to avoid using the data when is undefined
.
useEffect(() => {
if(data){
console.log(data.test.test);
}
}, [data])
CodePudding user response:
You have two solutions. As @Woohaik has already mentioned, checking for data existence in the useEffect. I'd implement a guard:
useEffect(() => {
if (!data) return
console.log(data.test.test)
}, [data])
or you could make yourself acquainted with optional chaining (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining):
useEffect(() => {
console.log(data?.test?.test)
}, [data])