0

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.

1 Answer 1

2

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]) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.