Reputation: 327
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
});
}
}
Upvotes: 1
Views: 419
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
Reputation: 1864
This is what is happening:
this.state.searchValue
gets truthy - it updates stateWhat should you do:
componentDidUpdate(prevProps, prevState)
if(this.state.searchValue !== "" && this.state.searchValue !== prevState.searchValue) {...}
Upvotes: 1
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:
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