1
votes

So I have a button. When you click on that button, it takes you to an onSubmit function which looks like this:

  onSubmit(e) {
      e.preventDefault();
      this.props.nextSentence(); //this is async

      this.setState({ //this is not yet updating with the right values then
          inputField: this.props.activePupil.name
      });
  }

However: this.props.nextSentence(); is async, so when I set my state immediately after, there are no changes. Right now I have a second button which refers to a second function which just sets the state again. I would like to have this happen automatic though. How could I do this?

1
why don't you want for the result and then set state? using then(...) this.props.nextSentence.then(value => this.setState ({ ... }))Lyubomir
Perhaps you can try to set your state as a props and change it in the parent that contain the callback nextSentence ?Alexandre Nicolas
You can use promises to handle this scenarioRicha Garg

1 Answers

2
votes

async actions are normally either Promises or functions with callbacks.

In case of a Promise you need to use .then like below

this.props.nextSentence().then(() => {
  this.setState({...});
})

And in case of a function with callback

this.props.nextSentence(() => {
  this.setState({...})
})

However keep in mind than you can get the returned response of your async action and use it to update your state. which is normally the case.

For example

//here response is a json object returned from server     
this.props.nextSentence().then((response) => {
  this.setState({
    data: response.data
  });
})