UNPKG

@veracity/vui

Version:

Veracity UI is a React component library crafted for use within Veracity applications and pages. Based on Styled Components and @xstyled.

43 lines (41 loc) 1.46 kB
import { useControlled, useIsMounted } from "../utils/react.js"; import { getPaginationItems } from "./helpers.js"; import { useEffect } from "react"; //#region src/pagination/usePagination.ts /** Hook to manage pagination data and state in controlled or uncontrolled way. */ function usePagination(props) { const { count, defaultPage = 1, onPageChange: onPageChangeProp, page: pageProp, pageSize } = props; const [page, onPageChange, { isControlled, reset }] = useControlled({ defaultValue: defaultPage, onChange: onPageChangeProp, value: pageProp }); useEffect(() => { !isControlled && onPageChangeProp?.(defaultPage); }, []); /** In uncontrolled mode, reset pagination whenever pageSize changes (apart from initialization). */ useEffect(() => { isMounted() && reset(); }, [pageSize]); const isMounted = useIsMounted(); /** How many pages are there in total. */ const pageCount = count > 0 && pageSize > 0 ? Math.ceil(count / pageSize) : 0; /** Array of navigation items, like buttons or arrows. */ const items = getPaginationItems(page, pageCount); /** First item displayed on the current page. */ const rangeStart = (page - 1) * pageSize + 1; return { count, items, onPageChange, page, pageCount, pageSize, rangeEnd: page === pageCount ? count : page * pageSize, rangeStart }; } //#endregion export { usePagination as default }; globalThis.__vuiVersion__ = "5.3.1" //# sourceMappingURL=usePagination.js.map