mardi 23 juin 2020

What is the correct pattern for making sure the state is current before submitting data

I'm using state to store and pass the values of inputfields. And also to signal when to upload data.

state: { value: 123, upload: false }

componentDidUpdate() {
  if(this.state.upload) {
    this.setState({ upload: false });
    axios.post(this.state.value) //simplified  
  }

}

<input onChange={(e) => this.setState({ value: e.currentTarget.value * 2})} /> //Has to be controlled component

<button onClick={() => this.setState({ upload: true}) />

Now a user types something into the input, and clicks the submit button. Both events fire, async.

  1. How do I make sure that the upload uses the current content of the input? The inputs onChange event could fire after the onClick.

  2. How do I make sure upload doesn't get happen twice, once from the button click and then from the onChange before upload is set to false again?

Aucun commentaire:

Enregistrer un commentaire