( options: UsePaginationOptions, )
| 15 | }>; |
| 16 | |
| 17 | export function usePagination( |
| 18 | options: UsePaginationOptions, |
| 19 | ): UsePaginationResult { |
| 20 | const { searchParams, onSearchParamsChange } = options; |
| 21 | const limit = DEFAULT_RECORDS_PER_PAGE; |
| 22 | const rawPage = Number.parseInt(searchParams.get(paginationKey) || "1", 10); |
| 23 | const page = Number.isNaN(rawPage) || rawPage <= 0 ? 1 : rawPage; |
| 24 | |
| 25 | return { |
| 26 | page, |
| 27 | limit, |
| 28 | offset: Math.max(0, (page - 1) * limit), |
| 29 | goToPage: (newPage) => { |
| 30 | const abortNavigation = |
| 31 | page === newPage || |
| 32 | !Number.isFinite(newPage) || |
| 33 | !Number.isInteger(newPage); |
| 34 | if (abortNavigation) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | const copy = new URLSearchParams(searchParams); |
| 39 | copy.set("page", newPage.toString()); |
| 40 | onSearchParamsChange(copy); |
| 41 | }, |
| 42 | }; |
| 43 | } |
no test coverage detected