Problems with typification of useQueries #10740
Replies: 4 comments
This comment was marked as spam.
This comment was marked as spam.
-
|
The type errors come from two things: The main fix: don't fight the generic parameters on export const useMultipleApiData = <TData, TResult = TData>(
// ...params
): MultipleApiDataResult<TResult> => {
const combine = useCallback(
(results: Array<UseQueryResult<MultipleApiData<TData>, FetchError>>) => {
return {
data: results
.filter((r) => r.data !== undefined)
.reduce<ResultMapping<TResult>>((acc, r) => {
acc[r.data!.variant] = r.data!.data as unknown as TResult;
return acc;
}, {}),
pending: results.some((r) => r.isPending),
};
},
[]
);
const queries = variants.map((variant) => ({
queryKey: [service, model, variant, token] as const,
queryFn: async () => {
// ...fetch logic
return { variant, data } satisfies MultipleApiData<TData>;
},
...queryOptions,
}));
return useQueries({
queries: queries as any, // dynamic arrays can't satisfy the tuple inference
combine,
}) as MultipleApiDataResult<TResult>;
};The Casting The |
Beta Was this translation helpful? Give feedback.
-
|
The root cause here is a fundamental TypeScript limitation with Here are the fixes: Fix 1: Explicitly Type the
|
Beta Was this translation helpful? Give feedback.
-
|
Two separate problems are stacking here, and the explicit generics are making both worse. The first type parameter of The combination that works without const combine = useCallback(
(results: UseQueryResult<MultipleApiData<TData>, FetchError>[]) => ({
data: results.reduce((acc, r) => {
if (r.data !== undefined) acc[r.data.variant] = r.data.data as unknown as TResult
return acc
}, {} as ResultMapping<TResult>),
pending: results.some((r) => r.isPending),
}),
[]
)
return useQueries({
queries: variants.map((variant) =>
queryOptions({
queryKey: [service, model, variant, token] as const,
queryFn: () => fetchVariant(variant),
...extraOptions,
})
),
combine,
})Your original annotation typed One more mismatch worth fixing: in |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have created a helper hook based on
useQueries. The idea is to encapsulate specific fetching logic inqueryFnand reformat results for easier use. It works as intended, but I can not fix typescript errors. The full code is:The main problem is with
@ts-expect-error- I didn't manage to fix it. The other problem is withas unknown as..., without it it doesn't work too.P.S. I have a similar helper hook for single
useQuery, and I've managed to typificate it without problems.Beta Was this translation helpful? Give feedback.
All reactions