Skip to content

Commit

Permalink
[DataGrid] Fix empty sort being saved in the sortModel (#12325)
Browse files Browse the repository at this point in the history
  • Loading branch information
MBilalShafi authored Mar 5, 2024
1 parent b03d011 commit 7736756
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export const useGridSorting = (
const existingIdx = sortModel.findIndex((c) => c.field === field);
let newSortModel = [...sortModel];
if (existingIdx > -1) {
if (!sortItem) {
if (sortItem?.sort == null) {
newSortModel.splice(existingIdx, 1);
} else {
newSortModel.splice(existingIdx, 1, sortItem);
Expand Down Expand Up @@ -191,7 +191,7 @@ export const useGridSorting = (
const sortItem = createSortItem(column, direction);
let sortModel: GridSortItem[];
if (!allowMultipleSorting || props.disableMultipleColumnsSorting) {
sortModel = !sortItem ? [] : [sortItem];
sortModel = sortItem?.sort == null ? [] : [sortItem];
} else {
sortModel = upsertSortModel(column.field, sortItem);
}
Expand Down
40 changes: 40 additions & 0 deletions packages/x-data-grid/src/tests/sorting.DataGrid.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,46 @@ describe('<DataGrid /> - Sorting', () => {
expect(getColumnValues(0)).to.deep.equal(['10', '0', '5']);
});

// See https://github.com/mui/mui-x/issues/12271
it('should not keep the sort item with `item.sort = null`', () => {
let apiRef: React.MutableRefObject<GridApi>;
const onSortModelChange = spy();
function TestCase() {
apiRef = useGridApiRef();
const cols = [{ field: 'id' }];
const rows = [{ id: 10 }, { id: 0 }, { id: 5 }];

return (
<div style={{ width: 300, height: 300 }}>
<DataGrid
apiRef={apiRef}
columns={cols}
rows={rows}
onSortModelChange={onSortModelChange}
/>
</div>
);
}

render(<TestCase />);
expect(getColumnValues(0)).to.deep.equal(['10', '0', '5']);
const header = getColumnHeaderCell(0);

// Trigger a `asc` sort
fireEvent.click(header);
expect(getColumnValues(0)).to.deep.equal(['0', '5', '10']);
expect(onSortModelChange.callCount).to.equal(1);
expect(onSortModelChange.lastCall.firstArg).to.deep.equal([{ field: 'id', sort: 'asc' }]);

// Clear the sort using `apiRef`
act(() => apiRef.current.sortColumn('id', null));
expect(getColumnValues(0)).to.deep.equal(['10', '0', '5']);
expect(onSortModelChange.callCount).to.equal(2);

// Confirm that the sort item is cleared and not passed to `onSortModelChange`
expect(onSortModelChange.lastCall.firstArg).to.deep.equal([]);
});

it('should always set correct `aria-sort` attribute', () => {
const cols = [{ field: 'id' }];
const rows = [{ id: 10 }, { id: 0 }, { id: 5 }];
Expand Down

0 comments on commit 7736756

Please sign in to comment.