The component should fetch new data from an API depending on the value of a Prop. That way - unfortunately - I cannot place the API call in the componentDidMoun()
method. I need to place it somewhere else to dynamically load it (when the Prop has changed).
I do not know where to place it best practice wise and avoid the problems with the asynchronous side effect through setState()
.
Let's say I have two components in App.js
. One which is a list picker where I can pick a country. The country get's passed to another component, which then fetches data from an API and shows the data fetched.
HI You can use componentDidUpdate
function to make the api call on the basis of condition that new props is not equal to old props.
componentDidUpdate(prevProps, prevState)
{
if(this.props[ANY_KEY] ! == prevProps[ANY_KEY]{
//MAKE THE API CALL HERE AND SET THE STATE IF YOU WANT TO
}
}