0

I have received

ERROR: "Uncaught RangeError: Maximum call stack size exceeded"

I suspect that this block of code in my componentWillUpdate method is the cause, since I've only been receiving the errors right after I added the code. Is there anything that I've done wrong here?

componentWillUpdate(nextProps, nextState) {

...

if (nextProps.show) {
  for (var i = 0; i < this.props.data.actions.length; i++) {
    if (this.props.data.actions[i].assignedTo !== this.state.userId && this.state.showActions === true) {
      this.setState({ showActions: false })
    }
    if (this.props.data.actions[i].assignedTo === this.state.userId && this.state.showActions === false) {
      this.setState({ showActions: true })
    }
  }
 }

...

}

nextProps.show is set to true when a button is clicked, then it checks whether the person assigned an action is the same as the user that is logged in, then it will set the state showActions to true. This state is used to display/hide rows if the conditions in the code are met

Aaqib
  • 9,942
  • 4
  • 21
  • 30
  • It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. As described https://stackoverflow.com/questions/6095530/maximum-call-stack-size-exceeded-error – Aaqib Nov 08 '17 at 13:26

3 Answers3

1

Since you are setting state, this would be calling componentWillUpdate again, thus this recursive call is the reason for stack exceeding.

Unlike componentWillMount(), we should not call this.setState() in componentWillUpdate(). The reason we do not call this.setState() is that the method triggers another componentWillUpdate(). If we trigger a state change in componentWillUpdate() we will end up in an infinite loop.

Muhammad Faizan
  • 1,709
  • 1
  • 15
  • 37
0

this.state is not yet mutated in componentWillUpdate.

As a reuslt, use nextState instead of this.state to verify the value was well after using this.setState:

componentWillUpdate(nextProps, nextState) {

...

if (nextProps.show) {
  for (var i = 0; i < this.props.data.actions.length; i++) {
    if (this.props.data.actions[i].assignedTo !== this.state.userId && nextState.showActions === true) {
      this.setState({ showActions: false })
    }
    if (this.props.data.actions[i].assignedTo === this.state.userId && nextState.showActions === false) {
      this.setState({ showActions: true })
    }
  }
 }

...

}
Damien Leroux
  • 11,177
  • 7
  • 43
  • 57
0

According to React componentWillUpdate docs:

Note that you cannot call this.setState() here; nor should you do anything else (e.g. dispatch a Redux action) that would trigger an update to a React component before componentWillUpdate() returns. If you need to update state in response to props changes, use componentWillReceiveProps() instead.

You should move your code to componentWillReceiveProps method.

pwolaq
  • 6,343
  • 19
  • 45