The useQueries
hook can be used to fetch a variable number of queries:
const results = useQueries([{ queryKey: ['post', 1], queryFn: fetchPost },{ queryKey: ['post', 2], queryFn: fetchPost },])
Options
The useQueries
hook accepts an array with query option objects identical to the useQuery
hook.
Returns
The useQueries
hook returns an array with all the query results.
Proposed docs to add to the useQueries
page:
TypeScript users
If you're using react-query
with TypeScript then generally you'll be able to benefit from type inference:
const resultWithAllTheSameTypes = useQueries([1, 2].map(x => ({ queryKey: `${x}`, queryFn: () => x })))// resultWithAllTheSameTypes: QueryObserverResult<number, unknown>[]const resultWithDifferentTypes = useQueries([1, 'two', new Date()].map(x => ({ queryKey: `${x}`, queryFn: () => x })))// resultWithDifferentTypes: QueryObserverResult<string | number | Date, unknown>[]
In both the examples above, no types were specified and the compiler correctly inferred the types from the array passed to useQueries
.
However, if you pass an array literal where different elements have a queryFn
with differing return types then you may encounter a compiler error. Consider:
const resultWithoutUsingMap = useQueries([{ queryKey: key1, queryFn: () => 1 },{ queryKey: key2, queryFn: () => 'two' },])
This will result in an error along the lines of Type '() => string' is not assignable to type 'QueryFunction<number>'.
This can be remedied by supplying the union of possible data types as a type parameter; like so:
const resultWithoutUsingMap = useQueries<number | string>([{ queryKey: key1, queryFn: () => 1 },{ queryKey: key2, queryFn: () => 'two' },])
The latest TanStack news, articles, and resources, sent to your inbox.