The functions all work as they are supposed to, however I would like the grand total to update after every tab or click outside of the inputs.
JSX:
<div className="w-full px-2 md:w-1/6">
<input type="text" placeholder="0.00" id="unit_price" onBlur={(e) => handlePriceChange(e)}/>
</div>
<div className="w-full px-2 md:w-1/6">
<input type="text" id="qty" onBlur={(e) => handleQtyChange(e)} />
</div>
Here are the handler functions:
const handleQtyChange = (e: any) => {
let parsedQty: number = parseFloat(e.target.value);
if(Number.isNaN(parsedQty)){
console.log("yes")
parsedQty = 0;
}
let final = parsedQty * price;
setQty(parsedQty);
setTotal(final);
lineTotal(final, count) //this fires the addLineTotal() function in the parent component
}
const handlePriceChange = (e: any): void => {
let parsedPrice: number = parseFloat(e.target.value);
if(Number.isNaN(parsedPrice)){
console.log("yes")
parsedPrice = 0;
}
let final = parsedPrice * qty;
setPrice(parsedPrice);
setTotal(final);
lineTotal(final, count) //this fires the addLineTotal() function in the parent component
}
Finally, here are the parent component callback functions to calculate line totals and then grand total.
const addLineTotal = (num: number, lineID: number): void => {
//calculates line total and executes grant total function
console.log("num => ", num);
let newTotal: number[] = [...total];
console.log("New total => ", newTotal)
newTotal[lineID] = num;
setTotal(newTotal);
calculateGrandTotal();
}
const calculateGrandTotal = () => {
//reduces the total array to single value
const reducer = (a: number, b: number) => a + b;
let gt: number = total.reduce(reducer);
console.log("GT => ", gt, "type of gt => ", typeof gt);
setGrandTotal(gt);
}
All numbers are calculating correctly, but I need to go back into the line then out for the grand total to calculate.