I have a react component, say, MyComponent with two props text and num which may change independently. Consider the following code:
componentDidUpdate(prevProps) {
if (this.props.text !== prevProps.text || this.props.num !== prevProps.num) {
this.getDataAPICall(this.props.text, this.props.num);
}
}
// Incoming data is dependent on both text and num
getDataAPICall(text, num) {
fetch(SOMEURL+'/text/num').then(d => d.json())
.then(data => {
setState({ renderdata: data });
})
}
If only one of the props is changed, there is no problem. But, when props change such that, say, text changes from "a" to "b" and num changes from 1 to 2, I realized that componentDidUpdate is called two times with text and num values:
text: "b", num: 1 and text: "b", num: 2.
Since num may or may not change (I can not know for sure), I have to call getDataAPICall with text: "b" and num: 1 as well. This causes two API calls (where the first one fetching the wrong data). Furthermore, depending on the completion time of the calls, the final state of the component may end up having the wrong data.
My question is: Is this the default behavior of componentDidUpdate or am I making a mistake in the parent component? If this is the default behavior, how can I avoid the first API call with the partially updated props?
Note: These two props are actually props of the parent component as well, which comes from redux store through mapStateToProps.
Thanks