Pulse Nova
Pulse Nova

Reputation: 327

ReactJS - Maximum update depth exceeded error

I'm facing an 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.

The code is as:

  componentDidUpdate() {
    this._updateLocalStorage();

    if (this.state.searchValue !== "") {
      this.setState({
        filteredNotes: this.state.notes.filter(
          note =>
            note.text
              .toLowerCase()
              .indexOf(this.state.searchValue.toLowerCase()) !== -1
        )
      });
    } else {
      this.setState({
        filteredNotes: this.state.notes 
      });
    }
  }

Maximum Update Depth Exceeded Error

Upvotes: 1

Views: 419

Answers (3)

xenon
xenon

Reputation: 307

It can be fixed by putting empty comparison if both the states are equal before the main state call. Also, I made a change in the else condition.

  componentDidUpdate(prevProps, prevState) {
    this._updateLocalStorage();

    if (this.state.searchValue !== "") {
      this.setState({
        filteredNotes: this.state.notes.filter(
          note =>
            note.text
              .toLowerCase()
              .indexOf(this.state.searchValue.toLowerCase()) !== -1
        )
      });
    } else if(prevState.filteredNotes === this.state.filteredNotes) {
      //do nothing
    } else if(this.state.searchValue === "") {
      this.setState({
        filteredNotes: this.state.notes 
      });
    }
  }

Upvotes: 1

Danko
Danko

Reputation: 1864

This is what is happening:

  1. in CDM once this.state.searchValue gets truthy - it updates state
  2. update on state trigger anothe CDM
  3. step 1. repeats
  4. step 2. repeats
  5. endless updates...

What should you do:

  1. update CDU to this componentDidUpdate(prevProps, prevState)
  2. update your conditionall to:
if(this.state.searchValue !== "" && this.state.searchValue !== prevState.searchValue) {...}

Upvotes: 1

keikai
keikai

Reputation: 15146

The componentDidUpdate would be called every time if there is a state change.

So you may need to use setState inside with caution.


Strict your condition for those setState. Perhaps something like below:

Some Notice Points:

  • object comparison
  • value/address reference
componentDidUpdate(pervProps, prevState) {
  if (prevState.filteredNotes !== this.state.filteredNotes) {
    this._updateLocalStorage();
    if (this.state.searchValue !== "") {
      this.setState({
        filteredNotes: this.state.notes.filter(
          note =>
            note.text
              .toLowerCase()
              .indexOf(this.state.searchValue.toLowerCase()) !== -1
        )
      });
    } else {
      this.setState({
        filteredNotes: this.state.notes 
      });
    }
  }
}

Upvotes: 1

Related Questions