Dependent Query Pattern
At my work we frequently run into situations where we need dependent queries for a bunch of items and I don't know a great pattern for it.
For example, let's say I have a list of cards and each card has an owner, but only the owner's ID. And say I have a separate endpoint to get details about the owner of the card using their ID. But I need to do that for each card and then combine all that into a "final card list" where each card has the details for the owner as well, not just the ID. How can I do that? Obviously it would be better if the api just returned the completed result with owner data already with each card, but i often don't have that luxury and even have more layers of dependent queries than just one layer in this example.
Crude example (I know I can't conditionally call the hook like that in the forEach, just an rough example of what I'm trying to do):
Right now we are just doing all the api calls in the query function of a single hook and returning the transformed cards. But, it would be great to separate the api calls if possible because other areas of the app need only the useCardOwnerDetails and we loose the caching benefits between the two areas
3 Replies
grumpy-cyan•10mo ago
Assuming you're truly stuck with this API, I would have all fetches in your single
queryFn
and then use select: data => data.find(entry => entry.ownerId === ownerId)
where you want just a single entries details.robust-apricot•10mo ago
Here's one example of how you can combine your queries. It's a pseudo-code to give you a hint. In this example
useCards
query populates the cache for individual card
. I assume you don't have the /cards/:id
endpoint, but it will change nothing in this example. useCardWithOwner
just combines data from two queries to achieve a desired structure. This way you will have separate cache entries and hooks for list of cards/individual card/card owner
, useCardWithOwner
will not have a cache entry, and data will be computed, but it's not a big deal.
robust-apricot•10mo ago
You can also use
select
with the useCards
to retrieve individual card when needed. Read this, it will help you https://tkdodo.eu/blog/react-query-data-transformations#3-using-the-select-optionReact Query Data Transformations
Learn the possibilities to perform the quite common and important task of transforming your data with react-query