tanstack query (requests in bulk vs individual)

- There are times where I need to make requests for specific objects from my database, but there can be many objects per page. Currently, I am just doing a useQuery per object that I need. That works fine but I think it may be better at this point to just request the specific objects that I need all at once, as in, make a request for the specific ids that I want in a single request. That way there are fewer requests and fewer calls to my database. The problem then, is that I cannot make use of the nice caching mechanism that tanstack query provides. An idea of what I'm going for is like this:
fn useItem(id: number) {
useQuery(['item', id], api.getItem(id), {...opts}),
}

async fn useManyItems(idList: number[]) {
// check if these items are currently being cached and remove them from the list if they are

// for those that are not cached, get them
const response = await api.getManyItems(idList)

// for the items in this response, map the values to the `singular item` type of query so that future calls to `useManyItems` with that id do not re-request it
}
fn useItem(id: number) {
useQuery(['item', id], api.getItem(id), {...opts}),
}

async fn useManyItems(idList: number[]) {
// check if these items are currently being cached and remove them from the list if they are

// for those that are not cached, get them
const response = await api.getManyItems(idList)

// for the items in this response, map the values to the `singular item` type of query so that future calls to `useManyItems` with that id do not re-request it
}
I skimmed the docs but didn't see anything pop out to me, does anyone know of anything that would provide this sort of function off the top of their head?
6 Replies
Neto
Neto12mo ago
You can fetch more data, fill the "singular" data that otherwise would be a db call When you would access the data in the component, the data would be already there, but you could fallback to fetch from the db
import_antigravity
fill the "singular" data that otherwise would be a db call
by this, do you mean queryClient.setQueryData() something like this?
Neto
Neto12mo ago
Yeah
import_antigravity
that does get me some of the way there
Huperniketes
Huperniketes12mo ago
Wouldn't prefetchQuery() be more like what you're looking for?
import_antigravity
no because that would still do the individual requests I want to do a single bulk request but make tanstack understand that that was actually the same thing as <n> different "individual" requests so future bulk requests would smartly ignore requesting for the same data and individual requests for items that have already been requested in a bulk request are also ignored