From b536b83d2754dd0be0d69646a0155d6bb32d7637 Mon Sep 17 00:00:00 2001 From: Martijn van den Broek Date: Fri, 27 Oct 2023 13:57:08 +0200 Subject: [PATCH] [DataGridPro] Fix useGridRows not giving error on reversed data --- .../src/tests/lazyLoader.DataGridPro.test.tsx | 24 +++++++++++++++++++ .../src/hooks/features/rows/useGridRows.ts | 11 ++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/grid/x-data-grid-pro/src/tests/lazyLoader.DataGridPro.test.tsx b/packages/grid/x-data-grid-pro/src/tests/lazyLoader.DataGridPro.test.tsx index b144e2d8640f5..903df7847f65d 100644 --- a/packages/grid/x-data-grid-pro/src/tests/lazyLoader.DataGridPro.test.tsx +++ b/packages/grid/x-data-grid-pro/src/tests/lazyLoader.DataGridPro.test.tsx @@ -171,4 +171,28 @@ describe(' - Lazy loader', () => { expect(apiRef.current.getRowNode(4)).to.not.equal(null); expect(apiRef.current.getRowNode(5)).to.not.equal(null); }); + + + it('should update rows when `apiRef.current.updateRows` with data reversed', () => { + render(); + + const newRows: GridRowModel[] = [ + { + id: 3, + first: 'Jim', + }, + { + id: 2, + first: 'Jack', + }, + { + id: 1, + first: 'Mike', + }, + ]; + + act(() => apiRef.current.unstable_replaceRows(0, newRows)); + expect(getColumnValues(1)).to.deep.equal(['Jim', 'Jack', 'Mike']); + }); + }); diff --git a/packages/grid/x-data-grid/src/hooks/features/rows/useGridRows.ts b/packages/grid/x-data-grid/src/hooks/features/rows/useGridRows.ts index 2562e1c3d932f..bf6ea676944a0 100644 --- a/packages/grid/x-data-grid/src/hooks/features/rows/useGridRows.ts +++ b/packages/grid/x-data-grid/src/hooks/features/rows/useGridRows.ts @@ -410,6 +410,7 @@ export const useGridRows = ( const dataRowIdToIdLookup = { ...gridRowsDataRowIdToIdLookupSelector(apiRef) }; const rootGroup = tree[GRID_ROOT_GROUP_ID] as GridGroupNode; const rootGroupChildren = [...rootGroup.children]; + const seenIds: GridRowId[] = []; for (let i = 0; i < newRows.length; i += 1) { const rowModel = newRows[i]; @@ -421,9 +422,11 @@ export const useGridRows = ( const [replacedRowId] = rootGroupChildren.splice(firstRowToRender + i, 1, rowId); - delete dataRowIdToModelLookup[replacedRowId]; - delete dataRowIdToIdLookup[replacedRowId]; - delete tree[replacedRowId]; + if (!seenIds.includes(replacedRowId)) { + delete dataRowIdToModelLookup[replacedRowId]; + delete dataRowIdToIdLookup[replacedRowId]; + delete tree[replacedRowId]; + } const rowTreeNodeConfig: GridLeafNode = { id: rowId, @@ -435,6 +438,8 @@ export const useGridRows = ( dataRowIdToModelLookup[rowId] = rowModel; dataRowIdToIdLookup[rowId] = rowId; tree[rowId] = rowTreeNodeConfig; + + seenIds.push(rowId); } tree[GRID_ROOT_GROUP_ID] = { ...rootGroup, children: rootGroupChildren };