From 29b36a4b045add88568abcebedc2f846cb1c6a93 Mon Sep 17 00:00:00 2001 From: Frederic Bahr Date: Tue, 18 Feb 2025 19:10:48 +0100 Subject: [PATCH] fix: prevent unnecessary pagination changes by fixing out-of-bounds check Fixes: https://github.com/KevinVandy/material-react-table/issues/1375 --- .../src/hooks/useMRT_Effects.ts | 9 ++-- .../stories/fixed-bugs/useEffects.stories.tsx | 41 +++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/packages/material-react-table/src/hooks/useMRT_Effects.ts b/packages/material-react-table/src/hooks/useMRT_Effects.ts index 2cae966dd..ce4ace2cf 100644 --- a/packages/material-react-table/src/hooks/useMRT_Effects.ts +++ b/packages/material-react-table/src/hooks/useMRT_Effects.ts @@ -69,9 +69,12 @@ export const useMRT_Effects = ( useEffect(() => { if (!enablePagination || isLoading || showSkeletons) return; const { pageIndex, pageSize } = pagination; - const firstVisibleRowIndex = pageIndex * pageSize; - if (firstVisibleRowIndex >= totalRowCount) { - table.setPageIndex(Math.ceil(totalRowCount / pageSize) - 1); + const totalPages: number = + totalRowCount > 0 ? Math.ceil(totalRowCount / pageSize) : 1; + const isOutOfBounds: boolean = pageIndex < 0 || pageIndex >= totalPages; + + if (isOutOfBounds) { + table.setPageIndex(totalPages - 1); } }, [totalRowCount, enablePagination, isLoading, showSkeletons]); diff --git a/packages/material-react-table/stories/fixed-bugs/useEffects.stories.tsx b/packages/material-react-table/stories/fixed-bugs/useEffects.stories.tsx index c21b22fe8..3f1314780 100644 --- a/packages/material-react-table/stories/fixed-bugs/useEffects.stories.tsx +++ b/packages/material-react-table/stories/fixed-bugs/useEffects.stories.tsx @@ -5,10 +5,12 @@ import MenuItem from '@mui/material/MenuItem'; import { type MRT_ColumnDef, type MRT_ColumnFiltersState, + MRT_PaginationState, MaterialReactTable, } from '../../src'; import { faker } from '@faker-js/faker'; import { type Meta } from '@storybook/react'; +import { Updater } from '@tanstack/react-table'; const meta: Meta = { title: 'Fixed Bugs/useEffects', @@ -323,3 +325,42 @@ export const DelayedFacetedValues = () => { /> ); }; + +export const PreventUnnecessaryPaginationChangeByOutOfBoundsCheck = () => { + const [pagination, setPagination] = useState({ + pageIndex: 0, + pageSize: 5, + }); + + const columns: MRT_ColumnDef[] = [ + { + accessorKey: 'firstName', + header: 'First Name', + }, + { + accessorKey: 'lastName', + header: 'Last Name', + }, + { + accessorKey: 'address', + header: 'Address', + }, + ]; + + const handlePaginationChange = (updater: Updater) => { + console.log('Pagination change should not be triggered'); + setPagination(updater); + }; + + return ( + + ); +};