So I created a investment calculator that takes inputs from a form and uses Recharts to render the return for a set time period of a year. The data gets calculated inside a useEffect in the InputForm.js component and pushed into an array. The array is exported and fed into the recharts line chart data property. The problem is i need a force update button to rerender the chart. I created a boolean with use state that changes every time an input is changed. Can I somehow use that to rerender the chart or is there a better way?
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;
})