|
| 1 | +import type { UseQueryOptions } from '@tanstack/react-query'; |
| 2 | +import { useQueries } from '@tanstack/react-query'; |
| 3 | + |
| 4 | +import type { ResourceError, ResourceName, ResourcePayload } from './resources'; |
| 5 | +import useApiFetch from './useApiFetch'; |
| 6 | +import type { Params as ApiQueryParams } from './useApiQuery'; |
| 7 | +import { getResourceKey } from './useApiQuery'; |
| 8 | + |
| 9 | +export interface ReturnType<R extends ResourceName, E = unknown> { |
| 10 | + isLoading: boolean; |
| 11 | + isPlaceholderData: boolean; |
| 12 | + isError: boolean; |
| 13 | + isSuccess: boolean; |
| 14 | + data: Array<ResourcePayload<R>> | undefined; |
| 15 | + error: ResourceError<E> | null | undefined; |
| 16 | +} |
| 17 | + |
| 18 | +export default function useApiQueries<R extends ResourceName, E = unknown>( |
| 19 | + resource: R, |
| 20 | + params: Array<ApiQueryParams<R, E>>, |
| 21 | + queryOptions: Partial<Omit<UseQueryOptions<ResourcePayload<R>, ResourceError<E>, Array<ResourcePayload<R>>>, 'queries'>>, |
| 22 | +) { |
| 23 | + const apiFetch = useApiFetch(); |
| 24 | + |
| 25 | + return useQueries<Array<UseQueryOptions<ResourcePayload<R>, ResourceError<E>>>, ReturnType<R, E>>({ |
| 26 | + queries: params.map(({ pathParams, queryParams, queryOptions, fetchParams, logError, chain }) => { |
| 27 | + return { |
| 28 | + queryKey: getResourceKey(resource, { pathParams, queryParams, chainId: chain?.id }), |
| 29 | + queryFn: async({ signal }) => { |
| 30 | + return apiFetch(resource, { pathParams, queryParams, logError, chain, fetchParams: { ...fetchParams, signal } }) as Promise<ResourcePayload<R>>; |
| 31 | + }, |
| 32 | + ...queryOptions, |
| 33 | + }; |
| 34 | + }), |
| 35 | + combine: (results) => { |
| 36 | + const isError = results.some((result) => result.isError); |
| 37 | + const isSuccess = results.every((result) => result.isSuccess); |
| 38 | + |
| 39 | + return { |
| 40 | + isLoading: results.some((result) => result.isLoading), |
| 41 | + isPlaceholderData: results.some((result) => result.isPlaceholderData), |
| 42 | + isError, |
| 43 | + isSuccess, |
| 44 | + data: isSuccess ? results.map((result) => result.data).flat() as Array<ResourcePayload<R>> : undefined, |
| 45 | + error: isError ? results.find((result) => result.error)?.error : undefined, |
| 46 | + } satisfies ReturnType<R, E>; |
| 47 | + }, |
| 48 | + ...queryOptions, |
| 49 | + }); |
| 50 | +} |
0 commit comments