I am calling an API that is displaying ID and Name in the table. I want to perfor sorting. I am using Material UI table. When the handleTableChange function triggers the API call(apiCall) inside this function goes on loop.
In the handleTableChange function I am performing sorting on each column and showing the 10 records per page
What is the write approch to make this call?
function Schedules(props) {
const [scheduleList, setScheduleList] = useState([]);
const [totalSize, setTotalSize] = useState(0);
const [sortQuery, setSortQuery] = useState("&sortDirection=desc");
const [reqParams, setReqParams] = useState("?offset=0&limit=10");
useEffect(() => {
apiCall(reqParams + sortQuery);
}, []);
let apiCall = (reqParams) => {
schedules.getSchedule("/xxxx" + reqParams)
.then((res) => {
console.log(res, 'res schedule');
if (res.data.metadata.outcome.status === 200) {
setScheduleList(res.data.data)
setTotalSize(res.data.totalCount)
} else {
setScheduleList([])
setTotalSize(0)
}
})
};
const handleTableChange = (tableFactors) => {
if (Object.keys(tableFactors).length === 0) {
return;
}
const { recordsPerPage, currentPage } = tableFactors;
//function for sort the columns
let sortingQuery = "";
if (tableFactors.sortData !== undefined) {
for (const [key, value] of Object.entries(tableFactors.sortData)) {
if (value !== "default" && key.includes("sort")) {
sortingQuery += `&sort=${key.replace(
"sort",
""
)}&sortDirection=${value}`;
}
}
}
// function for record per page
var offset = 0;
let limit = recordsPerPage || 10;
if (currentPage) {
offset = (currentPage - 1) * limit;
}
let reqPerPage = "?offset=" + offset + "&limit=" + limit;
apiCall(reqPerPage + sortingQuery);
setSortQuery(sortingQuery)
}
return (
<div>
<Table
id="scheduleGrid"
data={scheduleList}
totalSize={totalSize}
noDataText="No records found"
multisort={false}
columnResize
defaultSort={{ cret_ts: "desc" }}
columns={[
{
apiKey: "id",
columnText: "ID",
sort: true,
hidden: false,
filter: "text",
},
{
apiKey: "name",
columnText: "Name",
sort: true,
filter: "text",
hidden: false,
},
]}
handleTableChange={handleTableChange}
/>
</div>
);
}
export default Schedules;