T
TanStack3y ago
xenial-black

Typescript error for empty array with useQueries

In following this example for dependent queries with useQueries, https://tanstack.com/query/latest/docs/react/guides/dependent-queries#usequeries-dependent-query Typescript is reporting an error when passing in an empty array for queries. Here are two variants showing the error while trying to troubleshoot the issue, https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAbzgVwM4FMCKz1WO1OAXzgDMoIQ4ByAARgEMA7VRgYwGsB6KdBtmAFoAjjigBPanC5c4McWAIAuOFDYAodWwgt4YBlAYAbI+iPZc+VAEY4AXhQYLeAgAoAsgxgALAHSGmABNKVwBKOAAeOAAGXwBWOAB+RDhRS2U4AG0AXWI4FQR1OFSxKxVMwuLitIkAaXRxcupSCAhqbIAaIqqa8QAxJhUw+wA+OAAiADdjHHHuomz1IlCAbk0tHVY4fUMTM2crACZ7RyxSt0qS9NQVTx9-ZmCQYajYhOSK7uqxcXrGrPGLQg406XyuEgGQ3CdjG4wARgY5sUFvksotlisgA How does useQueries need to be typed so Typescript accepts an empty array for queries? I believe a solution could be to manually type the empty array [] as readonly [...QueriesOptions<T>], although for that would require QueriesOptions to be exported from @tanstack/*-query, which currently isn't
2 Replies
xenogeneic-maroon
xenogeneic-maroon3y ago
You would usually map through an array and have your queryKey + queryFn dependent on that. That seems to type fine as in the example in the docs. Modifying your example to follow the same structure seems to type correctly:
const queries = useQueries({
queries: Math.random() > 0.5 ? [] : [
].map(_ => ({
queryKey: ['foo'],
queryFn: () => "value"
}))
});
const queries = useQueries({
queries: Math.random() > 0.5 ? [] : [
].map(_ => ({
queryKey: ['foo'],
queryFn: () => "value"
}))
});
Sidenote: Note sure if intentional, but it seems like there is a typo in the docs.
const usersMessages = useQueries({
queries: userIds
? usersId.map((id) => {
return {
queryKey: ['messages', id],
queryFn: () => getMessagesByUsers(id),
}
})
: [], // if users is undefined, an empty array will be returned
})
const usersMessages = useQueries({
queries: userIds
? usersId.map((id) => {
return {
queryKey: ['messages', id],
queryFn: () => getMessagesByUsers(id),
}
})
: [], // if users is undefined, an empty array will be returned
})
userIds vs usersId after defined check.
xenial-black
xenial-blackOP3y ago
Looks like a typo @Dyrhoi thank you

Did you find this page helpful?