The component renders the sum , which was calculated by previous values.
I know how batches work and why is this. I could solve this by implementing a button and connect the button to a click event handler , but I would like to calculate the sum with onChange Event inside the calculate() funciton .
So I would like to handle the set state and the calculation process in the same function.
So my quiestion is how could I get the updated value of num1 and num2 , which was updated in the same batch:
setSum(parseFloat(**Updated**num1) parseFloat(**Updated**num2))
--
export default function Home() {
const [num1 , SetNum1] = useState(0.0)
const [num2 , setNum2] = useState(0.0)
const [sum, setSum] = useState(0.0)
const calculate = (e) => {
switch(e.target.id){
case 'num1':
SetNum1((prev) => {
return e.target.value
})
break;
case 'num2':
setNum2((prev) => {
return e.target.value
})
break;
}
setSum(parseFloat(num1) parseFloat(num2))
}
return (
<div>
<form>
<input type="number" className="form-control" id="num1" value={num1} onChange={(e) => calculate(e)} />
<input type="number" className="form-control" id="num2" value={num2} onChange={(e) => calculate(e)} />
Sum : {sum}
</form>
</div>
)
}
Is it possible to access the most recent num1 value after SetNum1 or I have to implement a button which calculates the sum?
CodePudding user response:
You want to listen for changes with useEffect
.
export default function Home() {
const [num1 , setNum1] = useState(0.0)
const [num2 , setNum2] = useState(0.0)
const [sum, setSum] = useState(0.0)
// execute the function whe num1 or num2 is changed
useEffect(() => {
setSum(parseFloat(num1) parseFloat(num2))
}, [num1, num2]);
return (
<div>
<form>
<input type="number" className="form-control" id="num1" value={num1} onChange={(e) => setNum1(e.target.value)} />
<input type="number" className="form-control" id="num2" value={num2} onChange={(e) => setNum2(e.target.value)} />
Sum : {sum}
</form>
</div>
)
}