Reputation: 178
What react life cycle should I use to update the local state that I have on my component with information that comes from an axios GET method?
So far I tried componentDidMount
but the axios is not completed there, so the prop is empty []
.
I also tried componentDidUpdate
. Surprisingly, the axios GET is completed here, but when I try to update the state, I get the warning for Maximum update depth exceeded.
A sample of my code follows:
componentDidUpdate() {
const {item} = this.props; // this is coming from axios
this.setState({
...
});
}
Upvotes: 0
Views: 82
Reputation: 2028
Check item equality value before setState function as below:
componentDidUpdate(prevProps) {
const {item} = this.props; // this is coming from axios
if(prevProps.item === item) return;
this.setState({
...
});
}
Upvotes: 1
Reputation: 4988
As they say in the documentation: https://reactjs.org/docs/react-component.html#componentdidupdate :
You may call setState() immediately in componentDidUpdate() but note that
it must be wrapped in a condition like in the example above, or you’ll
cause an infinite loop
You are calling setState all the time which causes an infinite loop.
Upvotes: 0