Skip to content

Commit 65b14e9

Browse files
committed
fix: stabilize pagination by resetting totalPages reference on chainId change
1 parent 5cfa44e commit 65b14e9

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

src/components/PaginatedNavigation.tsx

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
PaginationNext,
99
PaginationEllipsis,
1010
} from '@/components/ui/pagination';
11+
import useUserStore from '@/stores/useUser.store';
1112

1213
type PaginationControlsProps = {
1314
currentPage: number;
@@ -20,16 +21,32 @@ export const PaginatedNavigation = ({
2021
totalPages,
2122
onPageChange,
2223
}: PaginationControlsProps) => {
23-
// Keep stable totalPages to prevent pagination from disappearing during loading
24-
const lastValidTotalPagesRef = useRef<number>(1);
24+
const { chainId } = useUserStore();
2525

26-
// Only update the ref if we have a valid totalPages that's greater than or equal to the current one
27-
// This prevents the pagination from shrinking during loading states
28-
if (totalPages > 0 && totalPages >= lastValidTotalPagesRef.current) {
29-
lastValidTotalPagesRef.current = totalPages;
26+
const lastValidTotalPagesRef = useRef(1);
27+
const lastChainIdRef = useRef<number | null>(null);
28+
const chainChangeFrameRef = useRef(0);
29+
30+
const chainHasChanged = chainId !== lastChainIdRef.current;
31+
32+
if (chainHasChanged) {
33+
lastChainIdRef.current = chainId ?? null;
34+
chainChangeFrameRef.current = 0;
35+
} else {
36+
chainChangeFrameRef.current++;
37+
}
38+
39+
let stableTotalPages = lastValidTotalPagesRef.current;
40+
41+
const isRecentChainChange = chainChangeFrameRef.current <= 5;
42+
43+
if (chainHasChanged || isRecentChainChange) {
44+
stableTotalPages = Math.max(totalPages, 1);
45+
} else if (totalPages > 0 && totalPages >= lastValidTotalPagesRef.current) {
46+
stableTotalPages = totalPages;
3047
}
3148

32-
const stableTotalPages = lastValidTotalPagesRef.current;
49+
lastValidTotalPagesRef.current = stableTotalPages;
3350

3451
// Don't render pagination if no pages or invalid state
3552
if (!stableTotalPages || stableTotalPages <= 0 || currentPage <= 0) {

0 commit comments

Comments
 (0)