Home > front end >  Cannot update stateful object on onChange in React.js
Cannot update stateful object on onChange in React.js

Time:01-04

I am trying to update my object when getting number input. I can update "total" ( which I calculate based on input number ) but I cannot assign same input number to another object property --> ( quantity ) When I console log everything I get correct "total" but quantity remains 0.

    <Form.Item label="Quantity">
        <InputNumber onChange={handleAmount} />
</Form.Item>

//////////////////////////////

 const handleAmount = (amount) => {
    
            setOrderlist ({...orderlist, total : orderlist.price*amount});
            setOrderlist ({...orderlist, quantity: amount});
}

CodePudding user response:

You are overwriting your state, do it in one go instead

setOrderlist ({...orderlist, total: orderlist.price*amount, quantity: amount}});

CodePudding user response:

You do not need to call setOrderList twice.

You can just do a single:

const handleAmount = (amount) => { 
  setOrderList({ ...orderList, total: orderList.price * amount, quantity: amount })
}

  • Related