When passing options, useQuery does not accept types #8283
-
I created a custom hook that can accept options, and in theory, if you pass initialData into it, for example, then data should not be undefined interface UseCardServicesParams {
cardClientId: CardModel["card_client_id"] | undefined
options?: Omit<UseQueryOptions<ServiceModel[]>, "queryKey" | "queryFn">
}
export function useServices({ cardClientId, options }: UseCardServicesParams) {
const client = useClient()
const query = useQuery({
...options,
queryKey: ["services", cardClientId],
queryFn: () =>
client
.get(`/api/v1/cp/cards/${cardClientId}/services`)
.then(({ data }) => serviceSchema.array().parse(data)),
})
return query
} Despite this, data remains undefined const initialData = useLoaderData() as ServiceModel[]
const { data } = useServices({
cardClientId,
options: {
initialData,
},
}) Is it possible to fix this? So far I have found only this way interface ServicesQueryParams {
client: AxiosInstance
cardClientId: CardModel["card_client_id"]
}
export function servicesQuery({ client, cardClientId }: ServicesQueryParams) {
return {
queryKey: ["services", cardClientId],
queryFn: () =>
client
.get(`/api/v1/cp/cards/${cardClientId}/services`)
.then(({ data }) => ({ services: serviceSchema.array().parse(data) })),
} satisfies UseQueryOptions
} And then do this const client = useClient()
const initialData = useLoaderData() as ServiceModel[]
const { data } = useQuery({
...servicesQuery({ client, cardClientId }),
initialData,
}) Is it possible to somehow make it so that in the first case the data type is not undefined? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
this is a feature we have achieved with overloads in TypeScript. If you build your custom abstraction and want that, you need to either define overloads yourself or use conditional return types. My suggestion is to use |
Beta Was this translation helpful? Give feedback.
this is a feature we have achieved with overloads in TypeScript. If you build your custom abstraction and want that, you need to either define overloads yourself or use conditional return types.
My suggestion is to use
queryOptions
instead of building custom abstractions: typescript playground