I’m trying to get the sum of and deduction of a calculated field in a the result form, though is working but not working correct this is my code the issue is the if i type 10 to the price field i’d get 1 in the result and if i increase with 100 the result field will be 10, if i should remove 0 from the price field the result field increment to 100 kind of confuse this is my code here
const [price, setPrice] = useState(0)
const [setamount, setCodAmount] = useState(0)
const [result, setResult ] = useState(0)
const num1 = parseFloat(price)
const num2 = parseFloat(setamount)
const handleSetPrice = (e) => {
setPrice(parseFloat(e.target.value))
setResult(price)
console.log(price)
}
const handleSetCodAmount = (e) => {
const codamount = e.target.value
setCodAmount(codamount)
const sum = num1 - num2;
setResult(sum)
}
<input
type="number"
value={price}
onChange={handleSetPrice}
/>
<input
type="number"
value={setamount}
onChange={handleSetCodAmount}
/>
<input readOnly
type="text"
className="form-control"
value={result}
/>
i tried doing this 1000 - 100 = 990
expecting 900
3
Answers
Here is the codesandbox link: https://codesandbox.io/s/gifted-curran-tkq7yz?file=/demo.js
You don’t need num1 and num2 for this. Because, num1 and num2 variables outside the function, which are not updated dynamically with the latest values of price and setamount
I am not sure what you want, but i know where the error comes from.
You are doing the operation
num1 - num2
inhandleSetCodAmount
right after usingsetCodAmount
, so at this precise moment,num2
still has the previous value (because React update the state asynchronously for performance reason).A better usage would be to use the hook
useEffect
every timeprice
orsetamount
is updateduseState
updates the state variable for next render, see the related docs. Thus, thesetResult(price);
inhandleSetPrice
will use outdated value.The
result
gets different value based on whichonChange
function is called. Instead of usinguseState
for result, you could just normalconst
variable for it. The value of the variable is calculated on each render.