Nika Roffy
Nika Roffy

Reputation: 941

ComponentDidUpdate is not working properly

I'm trying to do setState in the componentDidUpdate. I did some research and read that I have to put some condition before making setState so it wont create forever loop but it did not work.

Any suggestions please?

Here is my code

 componentDidUpdate() {
const { isAuthenticated, navigation,actions } = this.props;
try {
  if (isAuthenticated) {
    navigation.navigate({ routeName: 'AlternatePhrase' });
    this.setState({isCreating:false})
  }
} catch (e) {
    console.log('--------e', e);
}
}

I'm getting this error:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Upvotes: 0

Views: 218

Answers (1)

larz
larz

Reputation: 5766

Check out the docs for componentDidUpdate and you'll see that you're given access to prevProps. The condition to avoid a loop is to check to see if isAuthenticated changed during the update and only if it did, then continue with your flow:

componentDidUpdate(prevProps) {
  const { isAuthenticated, navigation } = this.props;
  if (prevProps.isAuthenticated !== isAuthenticated) {
    try {
      if (isAuthenticated) {
        navigation.navigate({ routeName: 'AlternatePhrase' });
        this.setState({isCreating:false})
      }
    } catch (e) {
      console.log('--------e', e);
    }
  }
}

Upvotes: 1

Related Questions