T
TanStack3y ago
wise-white

Handling loading of multiple queries

Hi, I'm curious. How do people generally handle initial loading in the case of React components which use data from multiple queries ? For instance, say I have a component which displays a spinner while waiting on 4 different queries. Typically I'd just add a loading variable thus :
const loading = dataA.isLoading || dataB.isLoading // etc...
const loading = dataA.isLoading || dataB.isLoading // etc...
and then use that as a condition in the render, but it seems clunky. Maybe chop the component in 2 with a wrapper that handles loading? Any other way of doing it? Cheers
4 Replies
exotic-emerald
exotic-emerald3y ago
Hi, you could also combine into a single query the results of others. Not at the component level (several useQuery calls) but inside the queryFn of a dedicated query. From the component PoV, you would have something like:
const queryClient = useQueryClient()
const queryRes = useQuery(combinedKey, async () => {
const dataA = await queryClient.fetchQuery(objectAQueryKey, objectAQueryFn)
const dataB = await queryClient.fetchQuery(objectBQueryKey, objectBQueryFn)
return [...dataA, ...dataB] // or something else
})
const queryClient = useQueryClient()
const queryRes = useQuery(combinedKey, async () => {
const dataA = await queryClient.fetchQuery(objectAQueryKey, objectAQueryFn)
const dataB = await queryClient.fetchQuery(objectBQueryKey, objectBQueryFn)
return [...dataA, ...dataB] // or something else
})
wise-white
wise-whiteOP3y ago
Interesting. It would require me to do some refactoring given that I've mostly been wrapping queries in dedicated custom hooks containing everything the query needs (retrieval, schema validation, mapping).
exotic-emerald
exotic-emerald3y ago
Yep indeed. You could have a look here for an example on how we setup such a mechanism => https://codesandbox.io/s/fi882o
GLabat
CodeSandbox
react-query and queries composition - CodeSandbox
Illustrate how queries can be composed into a new one to simplify usage.
wise-white
wise-whiteOP3y ago
that said I'd still have to do isloading etc checks everywhere to satisfy Typescript whereas with a Container/Presentation component split, the presentation component needn't concern itself with all that... or an additional hook that handles all the individual RQ queries (less refactoring for now)...

Did you find this page helpful?