My component currently looks as follows:
import React, { useEffect, useState } from "react";
import Table from "../../../../Table/Table";
import { getBalance } from "../../../../../datasource/Financials";
export default function BalanceSheet() {
const [data, setData] = useState();
startYear = ??;
endYear = ??;
useEffect(() => {
const promise = getBalance(startYear, endYear);
promise.then((data) => {
setData(data);
});
}, []);
return data ? (
<>
<h2>Balance Sheet</h2>
<select id="currency">
<option value="USD">USD</option>
</select>
<select id="startYear">
<option value="2017" selected>2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
<select id="endYear">
<option value="2020" selected>2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
<Table
theadData={Object.keys(data.data[0].facts)}
tbodyData={data.data[0].facts}
/>
;
</>
) : (
"Sorry could not get data. Please try again."
);
}
I'm hoping to pass startYear
and endYear
into getBalance()
(which makes the api call) so that the page will automatically re-make the api call when a user changes either of the selects. Anyone know of an easy way to do this?
CodePudding user response:
If you wanna re-render your component with changes of your variables you should set them as state and pass them as dependencies to your useEffect:
const [startYear, setStartYear] = useState()
const [endYear, setEndYear] = useState()
useEffect(() => {
const promise = getBalance();
promise.then((data) => {
setData(data);
});
}, [startYear, endYear]);
<select id="startYear" onChange={(event) => setStartYear(evene.target.value)}>
<option value="2017" selected>2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
<select id="endYear" onChange={(event) => setEndYear(event.target.value)}>
<option value="2020" selected>2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>