import type { QueryKey, UseQueryOptions } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query'; import type { Params as FetchParams } from 'lib/hooks/useFetch'; import type { ResourceError, ResourceName, ResourcePathParams, ResourcePayload } from './resources'; import useApiFetch from './useApiFetch'; export interface Params> { pathParams?: ResourcePathParams; queryParams?: Record | number | boolean | undefined>; fetchParams?: Pick; queryOptions?: Omit, ResourceError, D>, 'queryKey' | 'queryFn'>; queryKey?: QueryKey; } export function getResourceKey(resource: R, { pathParams, queryParams }: Params = {}) { if (pathParams || queryParams) { return [ resource, { ...pathParams, ...queryParams } ]; } return [ resource ]; } export default function useApiQuery>( resource: R, { queryOptions, pathParams, queryParams, queryKey, fetchParams }: Params = {}, ) { const apiFetch = useApiFetch(); return useQuery, ResourceError, D>({ // eslint-disable-next-line @tanstack/query/exhaustive-deps queryKey: queryKey || getResourceKey(resource, { pathParams, queryParams }), queryFn: async({ signal }) => { // all errors and error typing is handled by react-query // so error response will never go to the data // that's why we are safe here to do type conversion "as Promise>" return apiFetch(resource, { pathParams, queryParams, fetchParams: { ...fetchParams, signal } }) as Promise>; }, ...queryOptions, }); }