简体   繁体   中英

React axios post request and setState on props change

I have a react app and I am using geolocated to get users location.

Following the instructions for the initialization I have wrapped the component:

export default geolocated({
    positionOptions: {
        enableHighAccuracy: true,
    },
    userDecisionTimeout: 15000,
})(ShowPois);

As soon as the user accepts (allows) the location finding on the browser I want two things to happen.

First I need to set a flag when then location is available to the app, so I have this:

static getDerivedStateFromProps(props, state) {
        if (!state.geolocatedReady && props.coords) {
            return {
                geolocatedReady: true
            }
        }
        return null;
    }

Notice that props.coords comes from geolocated

The second thing is that I want to complete an input box with the address of the location found. In order to do this I have to do a post request to an api to get the address, but the problem is I cannot use the getDerivedStateFromProps() method because the method must return a value, not a promise (made by axios post request).

So how can I make a post request and then set the state when a prop changes in the component?

getDerivedStateFromProps is only for edge cases . The case you have here sounds like a fit for componentDidUpdate .

componentDidUpdate() {
  if(!this.state.geolocatedReady && this.props.coords) {
    this.setState({
      geolocatedReady: true,
    });
    this.getAddress(this.props.coords);
  }
}
getAddress = async (coords) => {
  const address = await mapApi.getAddress(coords);
  // or whatever you want with it.
  this.setState({
   address 
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM