Batching single queries for better caching?
Hi all, let's say I have a situation where I'm fetching a paginated list of a users todos and then as a dependent query I want to fetch extra details about those todos. The issue I'm running into is that a page of todos can change based on sort/filter etc so I can end up fetching details of the same todo multiple times if the set of IDs on the page changes as those IDs are in my query key for the details.
For example:
1. I have todos with IDs 1, 2, and 3 on page 1, my dependent query fetches with key ['todos', 'details', [1, 2, 3]]
2. User sorts by name
3. Now todos 1, 4, and 5 on page 1, my dependent query fetches with key ['todos', 'details', [1, 4, 5]] and refetches the data for ID 1
Would it be better practice to create a separate query for each ID so the cache can pull based on specific ID? What if I have 50 todos to fetch?
8 Replies
ratty-blush•2y ago
Batching Requests | TanStack Query Docs
Many times we want to batch the requests a program(or component) does into one single request that fetches all the data items needed to execute(render) the program.
Lets say you have a component `` that internally fetches the user data and displays the user details. But it might be used arbitrarily on the page, for example in a user list, but ...
ratty-blush•2y ago
Why does one endpoint not deliver enough information for your list?
automatic-azureOP•2y ago
it would be very slow to pull all of the data at once, we make the 2nd fetch in the background
I think that batcher will do the trick! Thanks!
automatic-azureOP•2y ago
Huh, React doesn't seem to like it when you map to a query.
The code above gives me React error 311 https://legacy.reactjs.org/docs/error-decoder.html/?invariant=311
React - Error Decoder
A JavaScript library for building user interfaces
stormy-gold•2y ago
what does useNodes return?
automatic-azureOP•2y ago
The basic information of the node, so in this example something like just the nodes ID and Name. Then the details fleshes out the node with a much more detailed and expensive call.
The UI shows just the node name and when a user expands it shows the fleshed out details but we like to background the details so it's snappy when expanding without affecting the initial load.
The solution I'm currently trying is include the calls in a react component which is mapped onto the page, though in my real usecase this isn't very convenient. I would love to be able to use a map like what's giving me an error instead.
stormy-gold•2y ago
Can you show a codesandbox with this error?
automatic-azureOP•2y ago
Yeah let me put one together