I have added sort in my custom table. Sorting is working if I see it in console, It shows the data is getting updated.
But my TableBody is not getting updated after once.
Not sure what's happening.
TableWrapper.js
const TableWrapper = ({...props}) => {
const { tableData, columns } = props;
const [ visibleData, setVisibleData ] = useState([])
const sortColumn = (dataIndex, sortOrder) => {
let sortedData = tableData.data.firstResponse.sort(function(a, b){
if(a.dataIndex < b.dataIndex) return -1; // Ascending Order
if(a.dataIndex > b.dataIndex) return 1; // Descending Order
return 0; // Default
})
if (sortOrder === 'desc') {
sortedData.reverse();
}
console.log(dataIndex, sortOrder)
console.log(sortedData)
setVisibleData(sortedData);
}
return (
<>
<table>
<TableHead headers={columns} isCheckBox={true} isSelectAll={selectAll} selectAllChecked={selectAllChecked} sortColumn={sortColumn} />
<TableBody rows={tableData} tableData={visibleData} headers={columns} isCheckBox={true} isSelectAll={selectAll} isCheckBoxChecked={selectedCheckBox} />
</table>
</>
);
};
export default TableWrapper;
TableHead.js
const TableHead = ({...props}) => {
const { headers, isCheckBox, isSelectAll, selectAllChecked, sortColumn } = props;
const [sortorState, setSortorState] = useState("desc");
const checkRef = useRef();
const getSortorState = sortorState => {
switch (sortorState) {
case "asc":
return "desc";
case "desc":
return "asc";
default:
return "desc";
}
};
const handleSorterChange = (dataIndex, sortOrder) => {
const updatedSortorState = getSortorState(sortOrder);
setSortorState(updatedSortorState);
sortColumn(dataIndex, updatedSortorState)
};
return (
<thead>
<tr>
{
isCheckBox &&
<th key={`table-header-checkBox`}><input id="select-all-checkBox" type="checkbox" onClick={selectAllChecked} ref={checkRef} /></th>
}
{headers.map(item => {
const { key, field, style, header, sortable} = item
return (
<>
{sortable ?
<th
className={"table-header" + " sortable"}
onClick={() =>
handleSorterChange(field, sortorState)
}
>
<span>{header}</span>
</th>
:
<th
key={`table-header-${key}`}
style={style}>
{header}
</th>
}
</>
)})}
</tr>
</thead>
);
};
export default TableHead;
I need some help on this, why It's not getting updated.
Or is there any better way to achieve the sorting?
In the picture, I am trying to sort the first name, If you see the console the data is getting sorted but after one time the table data is not getting updated
