From ce011c4f14e1eb7a7330eb52154741d1872e877f Mon Sep 17 00:00:00 2001 From: Kartik sharma Date: Wed, 9 Jul 2025 10:45:46 +0530 Subject: [PATCH] There's an issue: Today's Attendance, when I went to page 2 and then changed the project, all the data was lost." --- src/hooks/usePagination.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/hooks/usePagination.js b/src/hooks/usePagination.js index b3e12b25..271e79c3 100644 --- a/src/hooks/usePagination.js +++ b/src/hooks/usePagination.js @@ -1,12 +1,31 @@ -import { useState, useMemo } from "react"; +import { useState, useMemo,useEffect } from "react"; const usePagination = (data, itemsPerPage) => { const [currentPage, setCurrentPage] = useState(1); - const totalPages = Math.ceil(data?.length / itemsPerPage); + + // const totalPages = Math.ceil(data?.length / itemsPerPage); + +// add this new line + const totalPages = useMemo(() => { + return Math.ceil((data?.length || 0) / itemsPerPage); + }, [data?.length, itemsPerPage]); + + useEffect(() => { + if (currentPage > totalPages && totalPages > 0) { + setCurrentPage(1); + } else if (!data || data.length === 0) { + setCurrentPage(1); + } else if (currentPage === 0 && totalPages > 0) { + setCurrentPage(1); + } + }, [data, totalPages, currentPage]); const currentItems = useMemo(() => { const startIndex = (currentPage - 1) * itemsPerPage; - return data?.slice(startIndex, startIndex + itemsPerPage); + + // return data?.slice(startIndex, startIndex + itemsPerPage); + return data?.slice(startIndex, startIndex + itemsPerPage) || []; + }, [data, currentPage, itemsPerPage]); const paginate = (pageNumber) => { -- 2.43.0