Skip to content

Commit bb63d28

Browse files
committed
fix: handle out-of-bounds pagination
Adds validation to redirect to first page when current page exceeds total pages
1 parent 9dd616c commit bb63d28

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

components/global/pagination/pagination.tsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { useCallback } from "react";
44
import PaginationButton from "./pagination-button";
5+
import { useRouter, useSearchParams } from "next/navigation";
56

67
interface PaginationProps {
78
searchParams: Record<string, string>;
@@ -18,10 +19,11 @@ export default function Pagination({
1819
itemsPerPage,
1920
parameterName = "p",
2021
basePath = "",
21-
currentPage = 1,
22+
currentPage,
2223
}: PaginationProps) {
2324
const totalPages = Math.ceil((totalItems || 0) / itemsPerPage);
2425
const pageNumber = currentPage || Number(searchParams[parameterName]) || 1;
26+
const { push } = useRouter();
2527

2628
const getPageHref = useCallback(
2729
(page: number) => {
@@ -59,6 +61,11 @@ export default function Pagination({
5961

6062
if (totalPages <= 1) return null;
6163

64+
if (pageNumber > totalPages) {
65+
// Redirect to last page if the current page is greater than the total number of pages
66+
push(getPageHref(totalPages));
67+
}
68+
6269
return (
6370
<div className="flex flex-col sm:flex-row gap-4 items-center justify-between w-full mt-4">
6471
<div className="flex items-center justify-start gap-2">

0 commit comments

Comments
 (0)