Replies: 2 comments
-
@TkDodo @artysidorenko looks like you updated the types most recently in #2634 , I'd appreciate any suggestions you might have! |
Beta Was this translation helpful? Give feedback.
0 replies
-
For those interested, I managed to find a solution: type ApiQueries<MethodNames extends readonly ApiMethodName[]> = {
[Index in keyof MethodNames]: {
methodName: MethodNames[Index];
params: Readonly<ApiParams<MethodNames[Index]>>;
} & UseQueryOptions<ApiResponse<MethodNames[Index]>>;
};
type GenerateReturn<MethodNames extends readonly ApiMethodName[]> = {
[Index in keyof MethodNames]: UseQueryResult<ApiResponse<MethodNames[Index]>>;
};
function useApiQueries<MethodNames extends readonly ApiMethodName[]>(
apiQueries: ApiQueries<MethodNames>
): GenerateReturn<MethodNames> {
const queries = apiQueries.map(({ methodName, params, ...options }) => {
return {
queryKey: [methodName, ...params],
queryFn: function () {
return api[methodName].apply(null, params);
},
...options,
};
});
return useQueries({
queries: queries,
}) as GenerateReturn<MethodNames>;
}
function Test() {
const [carVar, userVar, userVar2] = useApiQueriesVariant([
{ methodName: "getCar", params: [123] },
{ methodName: "getUser", params: [456] },
{ methodName: "getUser", params: [789] },
] as const);
return null;
} They key was to use |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
sandbox: https://codesandbox.io/p/sandbox/inspiring-leftpad-cm84cd?file=%2Fsrc%2Fmain.tsx%3A14%2C75
Given an API that looks something like:
I wanted to create a wrapper for
useQueries
,useApiQueries
:Currently, however, the type for the results array is a tuple of a union of all the possible return types i.e.
[UseQueryResult<User | Car, unknown>, UseQueryResult<User | Car, unknown>]
instead of
[UseQueryResult<Car, unknown>, UseQueryResult<User, unknown>]
.After looking at the types for
useQueries
, I saw that the hook accepts a genericT extends any[]
which is also passed intoQueriesResults<T>
to type the return value. After looking more closely atQueriesResults
, I determined thatT
is an array of{ queryFnData: infer TQueryFnData; error?: infer TError }
. With this in mind, I tried to create a mapped type that I could directly pass intouseQueries
asT
:but I'm getting the type error above. This is about where I got stuck, and I'm hoping others will have more insight. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions