How to call handleSubmit on a callback in a reaction

I need to wait for the callback before clicking place_id in the BrowserHistory

handleSubmit(event) {
    event.preventDefault();
    browserHistory.push(`/place_id/`+this.state.place.place_id);
}

The form submits automatically when a place is selected (which is good), but this.state.place is still null until the callback.

<form onSubmit={ this.handleSubmit.bind(this) }>
    <Autocomplete
        onPlaceSelected={(place) => {
            this.setState({place: place});
        }}
    />
</form>
+4
source share
3 answers

You can use something like this:

handleSubmit(event) {
  if (this.state.place) {
    browserHistory.push(`/place_id/`+this.state.place.place_id);
  } else {
    event.preventDefault();
  }
}

And this is the component:

  <form onSubmit={ this.handleSubmit.bind(this) } ref={(c) => this.frm = c}>
    <Autocomplete
        onPlaceSelected={(place) => {
          this.setState({place: place}, () => {this.frm.submit()});
        }}
    />
  </form>

The method callback setStatewill call the submitforms after , the place value has been set to state, and after that it browserHistory.pushwill be called inside handleSubmitbecause you have a place inside this.state.

+2
source

, , :

this.setState({place: place}, () => browserHistory.push(`/place_id/`+this.state.place.place_id));

, setState .

+2

changeRoute(place) {
  browserHistory.push(`/place_id/`+place.place_id);
}

  <form ref={(c) => this.frm = c}>
    <Autocomplete onPlaceSelected={this.changeRoute} />
  </form>
+1
source

Source: https://habr.com/ru/post/1684952/


All Articles