0

I have a function that calculate a "total price" based on a quantity argument passed from a different component (qty) and uses this to display a div:

 calculateTotal(qty) {
    var t;
    if (qty === 1) {
      t = 250 //total = total + 250
    }
    else if (qty > 1) {
      t = (qty * 250);  //total = qty * 250
    }
    else {
      t = this.state.total
    }
    return this.setState( { total: this.state.total + t })
     }

It would always display the previous calculation rather than the current. So if I enter 1, and then 2 as the quantity, the first time I enter 1, nothing is displayed, and the second time I press 2, the amount displayed is 250 (when it should be 500)

If anyone has any advice as to what the best course of action would be, it would be greatly appreciated.

If it helps, here is the function in the other component that triggers it (they enter a quantity, it sends that quantity to the function):

handleChange(event) {
  const key = Number(event.key)

  if (key === "Backspace") {
    this.setState({qty: 0})
    this.props.handleTotal(0);
  } else {
    this.setState({qty: key})
    this.props.handleTotal(this.state.qty);
  }
}
TomK
  • 117
  • 1
  • 12

2 Answers2

2

Looks like the problem is in the parent component's handleChange. You're calling setState and then hoping to pass the new value to the next function, but this.state.qty will be unchanged in the next line because setState is async.

handleChange(event) {
  const key = Number(event.key)

  if (key === "Backspace") {
    this.setState({qty: 0})
    this.props.handleTotal(0);
  } else {
    this.setState({qty: key})
    // this.props.handleTotal(this.state.qty); // <-- this will return the old value because setState above isn't done running
    this.props.handleTotal(key); // <-- try this instead
  }
}
Mickey
  • 570
  • 3
  • 11
  • Yes! that seemed to work, thank you. There are however some issues with my conditionals but I will work on debugging that ;) – TomK Aug 08 '19 at 20:37
  • and for more complicated cases, see also [When to use React setState callback](https://stackoverflow.com/a/42038724/1176601) – Aprillion Aug 08 '19 at 20:38
-1
 calculateTotal(qty) {
    var t;
    if (qty === 1) {
      t = 250 //total = total + 250
    }
    else if (qty > 1) {
      t = (qty * 250);  //total = qty * 250
    }
    else {
      t = (this.state.total * 2);
    }
    this.setState( { total:  t });
    return t;
     }

Please, check if this works out!

Ram Sankhavaram
  • 1,218
  • 6
  • 11