0

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?

I'm trying to stick to the react lifecycle, which is why I run axios in componentDidUpdate():

enter image description here

Master117
  • 660
  • 6
  • 21
  • 3
    I've got an impression that this aproach isn't sound at all. Why don't you extract the content of the input field at the moment of firing `onClick` event ? – px1mp Jun 23 '20 at 12:26
  • I would have to use a ref then, right? But isn't a ref only used for uncontrolled inputs? – Master117 Jun 23 '20 at 12:31
  • "*The inputs onChange event could fire after the onClick.*" - no. `onchange` fires before any other element gets focus. – Bergi Jun 23 '20 at 14:12
  • @Bergi yes but both call setState and those are async. – Master117 Jun 23 '20 at 16:00
  • @Master117 But they call `setState` in the right order, so you're good, no? – Bergi Jun 23 '20 at 16:01
  • @Bergi setState does not have to happen in order of call, thats the entire problem. – Master117 Jun 23 '20 at 20:35
  • 1
    @Master117 Are you sure there? Even if updates are batched and done *later*, [order is maintained](https://stackoverflow.com/q/48563650/1048572). – Bergi Jun 23 '20 at 20:45
  • 1
    Well, that solves my problem. I head heard differently. Thank you a lot @Bergi If you want to submit this as answer I will gladly accept it. – Master117 Jun 24 '20 at 06:47

0 Answers0