Así que creé una calculadora de inversión que toma entradas de un formulario y usa Recharts para generar el rendimiento durante un período de tiempo establecido de un año. Los datos se calculan dentro de un useEffect en el componente InputForm.js y se insertan en una matriz. La matriz se exporta y se introduce en la propiedad de datos del gráfico de líneas de recharts. El problema es que necesito un botón de actualización forzada para volver a representar el gráfico. Creé un booleano con estado de uso que cambia cada vez que se cambia una entrada. ¿Puedo usar eso de alguna manera para volver a representar el gráfico o hay una mejor manera?
var bigArr; var chartUpdate; function InputForm() { const [investinit, setInvestinit] = useState(""); const [deposit, setDeposit] = useState(""); const [interest, setInterest] = useState(""); const [chartUpdate, forceUpdate] = useState(false) function changeInit(e) { setInvestinit(parseInt(e.target.value)); forceUpdate (!chartUpdate); console.log(chartUpdate); } function changeDeposit(e) { if (e.target.value == "") { e.target.value = 0; } setDeposit(parseInt(e.target.value)); forceUpdate(!chartUpdate); console.log(chartUpdate); } function changeInterest(e) { setInterest(parseFloat(e.target.value)) forceUpdate(!chartUpdate); console.log(chartUpdate); } useEffect (() => { bigArr = [ { totalAmount: investinit, totalYield: 0, id: 0, totalMonthly: deposit }, ]; var monthlyInterest = interest / 1200 + 1; for (var i = 1; i < 13; i = i + 1) { var newTotal = investinit * Math.pow(monthlyInterest, i) + deposit * ((Math.pow(monthlyInterest, i) - 1) / (monthlyInterest - 1)); var totalMonthly = deposit * i; var gain = newTotal - (investinit + totalMonthly); bigArr.push({ totalAmount: newTotal, id: i, totalYield: gain, totalMonthly: totalMonthly, }); console.log(bigArr); } function Chart(chartUpdate) { const [, forceUpdate] = useReducer(x =>x+1,0) var money; useEffect(() => { forceUpdate() }, [chartUpdate]) return ( <div className="wrapper"> <div className="chart-wrap"> <h1>After a year your investment will be worth {money}$ </h1> <LineChart width={600} height={300} data={bigArr} margin={{ top: 20, right: 20, bottom: 5, left: 0 }}> <Line type="monotone" dataKey="totalAmount" stroke="black" /> <Line type="monotone" dataKey="totalYield" stroke="white" /> <CartesianGrid stroke="white" /> <XAxis dataKey="name" stroke="white" /> <YAxis stroke="white" /> <Tooltip /> </LineChart> <button></button> </div> </div> ); } export default Chart; })