Created
November 15, 2021 08:11
-
-
Save mithi/f023accdfd00cca7aef57d5457e3edb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback } from 'react' | |
const getTotalPages = (total: number, perPage: number) => Math.ceil(total / perPage) | |
const usePagination = () => { | |
const [state, setPaginationState] = useState<{ | |
totalItems: number | |
itemsPerPage: number | |
currentPage: number | |
}>({ totalItems: 0, itemsPerPage: 1, currentPage: 1 }) | |
const totalPages = Math.max(getTotalPages(state.totalItems, state.itemsPerPage), 1) | |
const currentStartItem = (state.currentPage - 1) * state.itemsPerPage | |
const currentEndItem = currentStartItem + state.itemsPerPage | |
const isLastPage = state.currentPage === totalPages | |
const isFirstPage = state.currentPage === 1 | |
const resetPaginationParams = useCallback((totalItems: number, itemsPerPage: number) => { | |
setPaginationState({ totalItems, itemsPerPage, currentPage: 1 }) | |
}, []) | |
const goToNextPage = useCallback(() => { | |
setPaginationState((prev) => { | |
return { ...prev, currentPage: isLastPage ? 1 : prev.currentPage + 1 } | |
}) | |
}, [isLastPage]) | |
const goToPreviousPage = useCallback(() => { | |
setPaginationState((prev) => { | |
return { | |
...prev, | |
currentPage: isFirstPage ? totalPages : prev.currentPage - 1, | |
} | |
}) | |
}, [isFirstPage, totalPages]) | |
const goToPage = useCallback( | |
(newPage: number) => { | |
if (newPage >= totalPages || newPage < 1) { | |
return | |
} | |
setPaginationState((prev) => ({ ...prev, currentPage: newPage })) | |
}, | |
[totalPages], | |
) | |
return { | |
resetPaginationParams, | |
goToNextPage, | |
goToPreviousPage, | |
currentPage: state.currentPage, | |
goToPage, | |
isLastPage, | |
isFirstPage, | |
totalPages, | |
currentStartItem, | |
currentEndItem, | |
} | |
} | |
export default usePagination |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment