react-sortable-table icon indicating copy to clipboard operation
react-sortable-table copied to clipboard

Table does not update when switching pages

Open sherman721 opened this issue 2 years ago • 1 comments

In my project, I am using these sortable tables on every user's home page. On the initial load it gets all the correct data, but when I switch to another user's page it keeps the first user's data. I believe the tableData (line 6 of Table.js) isn't getting updated in time and so the table does not update. Do you have any ideas on how to make the table wait to load until all the the tableData is properly sorted?

sherman721 avatar May 19 '23 22:05 sherman721

useSortableTable.js should be modified as below

import { useState , useEffect} from "react";

function getDefaultSorting(defaultTableData, columns) { const sorted = [...defaultTableData].sort((a, b) => { const filterColumn = columns.filter((column) => column.sortbyOrder); let { accessor = "id", sortbyOrder = "asc" } = Object.assign({}, ...filterColumn);

if (a[accessor] === null) return 1;
if (b[accessor] === null) return -1;

const ascending = a[accessor]
  .toString()
  .localeCompare(b[accessor].toString(), "en", { numeric: true });

return sortbyOrder === "asc" ? ascending : -ascending;

}); return sorted; }

export const useSortableTable = (data, columns) => { const [tableData, setTableData] = useState([]);

// Effect to update tableData when data or columns change useEffect(() => { setTableData(getDefaultSorting(data, columns)); }, [data, columns]);

const handleSorting = (sortField, sortOrder) => { if (sortField) { const sorted = [...tableData].sort((a, b) => { if (a[sortField] === null) return 1; if (b[sortField] === null) return -1; if (a[sortField] === null && b[sortField] === null) return 0; return ( a[sortField].toString().localeCompare(b[sortField].toString(), "en", { numeric: true, }) * (sortOrder === "asc" ? 1 : -1) ); }); setTableData(sorted); } };

return [tableData, handleSorting]; };

vimlesh1975 avatar May 10 '24 09:05 vimlesh1975