Skip to content

Commit c06cae9

Browse files
authored
fix: prevent unnecessary pagination changes by fixing out-of-bounds check (#1376)
Fixes: #1375
1 parent 223ee13 commit c06cae9

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

packages/material-react-table/src/hooks/useMRT_Effects.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,12 @@ export const useMRT_Effects = <TData extends MRT_RowData>(
6969
useEffect(() => {
7070
if (!enablePagination || isLoading || showSkeletons) return;
7171
const { pageIndex, pageSize } = pagination;
72-
const firstVisibleRowIndex = pageIndex * pageSize;
73-
if (firstVisibleRowIndex >= totalRowCount) {
74-
table.setPageIndex(Math.ceil(totalRowCount / pageSize) - 1);
72+
const totalPages: number =
73+
totalRowCount > 0 ? Math.ceil(totalRowCount / pageSize) : 1;
74+
const isOutOfBounds: boolean = pageIndex < 0 || pageIndex >= totalPages;
75+
76+
if (isOutOfBounds) {
77+
table.setPageIndex(totalPages - 1);
7578
}
7679
}, [totalRowCount, enablePagination, isLoading, showSkeletons]);
7780

packages/material-react-table/stories/fixed-bugs/useEffects.stories.tsx

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@ import MenuItem from '@mui/material/MenuItem';
55
import {
66
type MRT_ColumnDef,
77
type MRT_ColumnFiltersState,
8+
MRT_PaginationState,
89
MaterialReactTable,
910
} from '../../src';
1011
import { faker } from '@faker-js/faker';
1112
import { type Meta } from '@storybook/react';
13+
import { Updater } from '@tanstack/react-table';
1214

1315
const meta: Meta = {
1416
title: 'Fixed Bugs/useEffects',
@@ -323,3 +325,42 @@ export const DelayedFacetedValues = () => {
323325
/>
324326
);
325327
};
328+
329+
export const PreventUnnecessaryPaginationChangeByOutOfBoundsCheck = () => {
330+
const [pagination, setPagination] = useState({
331+
pageIndex: 0,
332+
pageSize: 5,
333+
});
334+
335+
const columns: MRT_ColumnDef<Person>[] = [
336+
{
337+
accessorKey: 'firstName',
338+
header: 'First Name',
339+
},
340+
{
341+
accessorKey: 'lastName',
342+
header: 'Last Name',
343+
},
344+
{
345+
accessorKey: 'address',
346+
header: 'Address',
347+
},
348+
];
349+
350+
const handlePaginationChange = (updater: Updater<MRT_PaginationState>) => {
351+
console.log('Pagination change should not be triggered');
352+
setPagination(updater);
353+
};
354+
355+
return (
356+
<MaterialReactTable
357+
columns={columns}
358+
data={[]}
359+
manualPagination={true}
360+
rowCount={0}
361+
enablePagination
362+
onPaginationChange={handlePaginationChange}
363+
state={{ pagination }}
364+
/>
365+
);
366+
};

0 commit comments

Comments
 (0)