Todas las funciones funcionan como se supone que deben hacerlo, sin embargo, me gustaría que el total general se actualice después de cada pestaña o haga clic fuera de las entradas.
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>Aquí están las funciones del controlador:
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 }Finalmente, aquí están las funciones de devolución de llamada del componente principal para calcular los totales de línea y luego el total general.
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); }Todos los números se calculan correctamente, pero necesito volver a la línea y luego salir para calcular el total general.