I have created a antd table in react with all the data. I needed to implement a sort function for two of the column Name
and Last Updated At
. For that I used the onChange={(val:any, filter:any, sorter:any})
function of the antd table and get the sorter
value from it and passing it a function called handleChange(val, sorter)
like this.
const handleChange = (val: any, sorter: any) => {
console.log(val, sorter);
if (sorter.order === "ascend") {
setSortOrderRaw("asc");
} else if (sorter.order === "descend") {
setSortOrderRaw("desc");
} else if (sorter.order === undefined) {
setSortOrderRaw("");
}
if (sorter.columnKey !== undefined) {
setSortFieldRaw(sorter.columnKey);
} else {
setSortFieldRaw("");
}
setPageSizeOther(val?.pageSize);
setCurrentPageOther(val?.current);
};
and added sortOrderRaw
and sortFieldRaw
as the dependencies of the useEffect
useEffect(() => {
getData();
}, [
pageSizeOther,
currentPageOther,
sortOrderRaw,
sortFieldRaw,
]);
So getData()
function should trigger every time sortOrderRaw
changes.
Issue is when I click the column header to sort, its order of sorting should be ascend
, descend
and then order should become undefined
but here its following order descend
, ascend
, ascend
, descend
, ascend
, ascend
. Bold and Italic ascend
should become undefined
then only getData()
function will trigger and populate the table without any sorting. but here as its getting ascend
in successive clicks getData()
function not triggering as the state is not changing.
Note: Even the tool tip also not showing click to cancel sorting
instead it showing click to sort ascending
for the successive clicks.
<Table
columns={columns}
dataSource={data}
loading={loading}
pagination={{
current: currentPage,
pageSize,
total,
showQuickJumper: true,
showSizeChanger: true,
}}
sortDirections={["ascend", "descend"]}
onChange={(val: any, filter: any, sorter: any, extra: any) => {
handleChange(val, sorter);
}}
/>
respective Columns
const columns: any[] = [
{
title: "Name",
dataIndex: "name",
key: "name",
width: "20%",
sorter: true,
},
{
title: "Last Updated On",
key: "CreatedAt",
sorter: true,
render: (_: any, record: any) => {
return DateTime.fromMillis(record.CreatedAt).toFormat(
"dd:MM:yyyy, hh:mm:ss a",
);
},
}
]