0

First I already has a working input Form and I can display the value of weight and price correctly.

But I have a question, when I change the Weight and Price, and I set a State value (totalPrice and payment) based on another State (weight and Price), the value doesn't get rendered immediately. I need to click the Button multiple time before the render display a correct value one by one (first click weight and price is correct, then when I click again the totalPrice, then I need to click again for payment to show the correct value).

This is a piece of my code, Thank You.

const [weight, setWeight] = useState(0)
const [pricePerGr, setPricePerGr] = useState(0)
const [totalPrice, setTotalPrice] = useState(0)
const [payment, setPayment] = useState(0)

const calculate = () => {
    setWeight(weightInput.value)
    setPricePerGr(priceInput.value)
    setTotalPrice(weight * pricePerGr)
    setPayment(totalPrice * 80 / 100)
}

<Button onClick={calculate}>Calculate</Button>

<div>
    weight: {weight}
    price per grams: {pricePerGr}
    Total Price: {totalPrice}
    Payment: {payment}
</div>
anggasantoso
  • 23
  • 1
  • 1
  • 5
  • https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – T.J. Crowder Aug 29 '21 at 10:48
  • 1
    `setTotalPrice` has no effect on the local copy of that state member you have in your `totalPrice` constant. You see the state change **later**, when your component function is called again to render updated state. Instead, store the calculation locally (say, `updatedTotalPrice`) and then use that for both `setTotalPrice(updatedTotalPrice);` and for `setPayment(updatedTotalPrice * 80 / 100);` – T.J. Crowder Aug 29 '21 at 10:50

0 Answers0