Skip to content

Commit

Permalink
use full list hook
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Jul 26, 2024
1 parent 9db127d commit ef013f1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/hooks/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { TypedUseLazyQuery } from "@reduxjs/toolkit/query/react"
import { useEffect, useState } from "react"

import type { Fields, ListArg, ListResult, Model } from "../utils/api"

export function useFullList<
QueryArg extends ListArg,
M extends Model<any>,
MFields extends keyof Omit<M, "id">,
ExtraFields extends Fields,
ResultType extends ListResult<M, MFields, ExtraFields>,
>(
useLazyListQuery: TypedUseLazyQuery<ResultType, QueryArg, any>,
arg: Partial<QueryArg> = {},
) {
const { limit = 150, offset = 0, ...filters } = arg

const [trigger] = useLazyListQuery()
const [isLoading, setIsLoading] = useState(true)
const [isError, setIsError] = useState(false)
const [error, setError] = useState<unknown>()
const [data, setData] = useState<ResultType["data"]>()

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)
})
}

useEffect(() => {
getPage(limit, offset, [])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [limit, offset])

return { data, isLoading, isError, error }
}
2 changes: 2 additions & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useFullList } from "./api"
import {
useSession,
useSessionMetadata,
Expand All @@ -13,6 +14,7 @@ export {
useCountdown,
useEventListener,
useExternalScript,
useFullList,
useLocation,
useNavigate,
useParams,
Expand Down

0 comments on commit ef013f1

Please sign in to comment.