-
-
Notifications
You must be signed in to change notification settings - Fork 87
Description
Describe the bug
I have been trying to track down a bug I have experienced in the InvenTree project
When using the useDataTableColumns hook, if the columns parameter changes, the order of rendered columns does not always match the provided order of columns.
To Reproduce
Steps to reproduce the behavior:
- Create a simple table with the
useDataTableColumnshook, e.g.
const myColumns = useMemo(() => {
return [
...
];
}, []);
const tableColumns = useDataTableColumns({
key: 'my-table',
columns: dataColumns,
});- Render the table, which stores the column order data to local storage
- Insert a new column (into
myColumns) which is not at the end - The table will be rendered with the new column at the end.
- Additionally, there may be multiple (ongoing, repeated) re-render hooks due to the mismatch of input and displayed column ordering
Additional calls to setColumnOrder do not seem to fix the problem, as the column order is "locked in" on first rendering call.
Expected behavior
The displayed column order always matches the order of the supplied columns.
Additional context
I believe that the bug arises from this line:
| setColumnsOrder(alignedColumnsOrder); |
In fact, I have resolved the issue entirely by commenting out this line.
So, this indicates that the alignedColumnsOrder is not being cached or updated correctly:
From:
| function alignColumnsOrder<T>(columnsOrder: string[], columns: DataTableColumn<T>[]) { |
function alignColumnsOrder<T>(columnsOrder: string[], columns: DataTableColumn<T>[]) {
const updatedColumnsOrder: string[] = [];
columnsOrder.forEach((col) => {
if (columns.find((c) => c.accessor === col)) {
updatedColumnsOrder.push(col);
}
});
columns.forEach((col) => {
if (!updatedColumnsOrder.includes(col.accessor as string)) {
updatedColumnsOrder.push(col.accessor as string);
}
});
return updatedColumnsOrder;
}This function orders the columns by first looking in the stored columns, and then appending any newly detected columns after that.
However, there is a logic or sequence error which means that the old columns order is always written back to the localStorage.