T
TanStack2y ago
metropolitan-bronze

Map queries in a single hook

I have a query from Tanstack-Query that returns an object with inside it an array of variable length (it can be an empty array). Inside this array, there are objects with one URL inside each object.
I want to fetch data for each URL inside one useQuery or useQueries hook.
Currently, I have this useQueries hook which returns an error that queries is undefined:
const [results] = useQueries({
queries: locationQuery.data?.areas.map((area) => ({
queryKey: [QueryKeys.AREA, area.url],
queryFn: () => getSingle(area.url), // getSingle is just a fetch
enabled: !!locationQuery.data.areas,
})),
});
const [results] = useQueries({
queries: locationQuery.data?.areas.map((area) => ({
queryKey: [QueryKeys.AREA, area.url],
queryFn: () => getSingle(area.url), // getSingle is just a fetch
enabled: !!locationQuery.data.areas,
})),
});
I need to keep the enabled field because locationQuery results from a query in the same file.
What do you think I should change to make the query works ?
1 Reply
quickest-silver
quickest-silver2y ago
const [results] = useQueries({
queries: locationQuery.data?.areas.map((area) => ({
queryKey: [QueryKeys.AREA, area.url],
queryFn: () => getSingle(area.url), // getSingle is just a fetch
enabled: !!locationQuery.data.areas,
}) ?? []),
});
const [results] = useQueries({
queries: locationQuery.data?.areas.map((area) => ({
queryKey: [QueryKeys.AREA, area.url],
queryFn: () => getSingle(area.url), // getSingle is just a fetch
enabled: !!locationQuery.data.areas,
}) ?? []),
});
Queries is undefined if data is undefined. Nullish Coescaling helps

Did you find this page helpful?