Table does not update when switching pages
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?
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]; };