React, updating state in child component using props after async call in parent component
You may use the componentWillReceiveProps
lifecycle method.
The first child component render some props like lat
and lng
are null, then you can do something like:
async componentWillReceiveProps(nextProps) {
if ( this.props.lat !== nextProps.lat || this.props.lng !== nextProps.lng ) {
const response = await YourAPICall(nextProps.lat, nextProps.lng)
this.setState(/* set your things here */)
}
}
Obviously this is just an outline...
Not sure why you use async/await instead of a normal fetch/axios call. In order to prevent entering in an infinite loop in your componentDidUpdate
as you mentioned you need to run a conditional statement, something like:
componentDidUpdate(prevState){
if (this.props.propertyYouWantToCheck !== prevState.propertyYouWantToCheck){
// set your state/logic here
}
}
Also you might want to consider to use fetch data only in the parent component and pass it down to the child component.