Deadpool
Deadpool

Reputation: 8240

useEffect dependency only if a certain variable is present then only watch it as dependency

I have the following set of running code:

useEffect(() => {
 if (field[1].isActive === true) {
  handleMore();
 }
}, [field[1].text]);

The issue is sometimes Field doesn't come in the json-response, so then this code shows an error. As I cannot put useEffect inside some conditional statement (as per React Guidelines, all useEffects should always run in same order), is there any way I may add some code in dependency such as [field.length? field[1].text: null]. I am not sure.

Can someone help?

Upvotes: 2

Views: 3047

Answers (3)

khaled-hbaieb
khaled-hbaieb

Reputation: 17

You can use the optional chaining https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Operators/Optional_chaining

like:

useEffect(() => {

 ...

}, [field?.[[1]]?.text]);

Upvotes: 2

Amit Chauhan
Amit Chauhan

Reputation: 6869

you can use optional chaining or && for this.

useEffect(() => {
 if (field?[1]?.isActive === true) {
  handleMore();
 }
}, [field?.[1]?.text]);

Or

useEffect(() => {
   if (field?[1]?.isActive === true) {
      handleMore();
   }
 }, [field && field[1] && field[0].text]);

Upvotes: 9

Dennis Vash
Dennis Vash

Reputation: 53884

The straight forward solution (since there is no context to this question) might be using optional chaining.

useEffect(() => {
 if (field?.[1]?.isActive === true) {
  handleMore();
 }
}, [field?.[1]?.text]);

Upvotes: 2

Related Questions