From 164653ab51edb1aa93f3b5efb62015832d965476 Mon Sep 17 00:00:00 2001 From: SKairinos Date: Tue, 30 Jul 2024 15:36:38 +0000 Subject: [PATCH] use pagination hook --- src/hooks/api.ts | 69 ++++++++++++++++++---------------------------- src/hooks/index.ts | 4 +-- 2 files changed, 29 insertions(+), 44 deletions(-) diff --git a/src/hooks/api.ts b/src/hooks/api.ts index aba6c8e..4f95670 100644 --- a/src/hooks/api.ts +++ b/src/hooks/api.ts @@ -1,49 +1,34 @@ -import type { TypedUseLazyQuery } from "@reduxjs/toolkit/query/react" -import { useEffect, useState } from "react" +import { type Dispatch, type SetStateAction, useState } from "react" -import type { Fields, ListArg, ListResult, Model } from "../utils/api" +export function usePagination( + options?: Partial<{ + page: number + limit: number + }>, +): [ + { page: number; limit: number; offset: number }, + Dispatch>, +] { + const { page = 0, limit = 150 } = options || {} -export function useFullList< - QueryArg extends ListArg, - M extends Model, - MFields extends keyof Omit, - ExtraFields extends Fields, - ResultType extends ListResult, ->( - useLazyListQuery: TypedUseLazyQuery, - arg: Partial = {}, -) { - const { limit = 150, offset = 0, ...filters } = arg + const [pagination, _setPagination] = useState({ + page, + limit, + offset: page * limit, + }) - const [trigger] = useLazyListQuery() - const [isLoading, setIsLoading] = useState(true) - const [isError, setIsError] = useState(false) - const [error, setError] = useState() - const [data, setData] = useState() + function setPagination( + value: SetStateAction<{ page: number; limit: number }>, + ) { + _setPagination(({ page: previousPage, limit: previousLimit }) => { + const { page, limit } = + typeof value === "function" + ? value({ page: previousPage, limit: previousLimit }) + : value - function getPage(limit: number, offset: number, _data: ResultType["data"]) { - trigger({ ...filters, limit, offset } as QueryArg) - .unwrap() - .then(({ data, offset, limit, count }) => { - _data.push(...data) - - offset += limit - if (offset < count) getPage(limit, offset, _data) - else { - setData(_data) - setIsLoading(false) - } - }) - .catch(error => { - setError(error) - setIsError(true) - }) + return { page, limit, offset: page * limit } + }) } - useEffect(() => { - getPage(limit, offset, []) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [limit, offset]) - - return { data, isLoading, isError, error } + return [pagination, setPagination] } diff --git a/src/hooks/index.ts b/src/hooks/index.ts index ce45825..9166904 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,4 +1,4 @@ -import { useFullList } from "./api" +import { usePagination } from "./api" import { useSession, useSessionMetadata, @@ -14,9 +14,9 @@ export { useCountdown, useEventListener, useExternalScript, - useFullList, useLocation, useNavigate, + usePagination, useParams, useSearchParams, useSession,