T
TanStack10mo ago
afraid-scarlet

Avoiding duplicate requests

I am using React Query to query an API for a list of members. The API returns a list of elements, one for each member. I use the list of member IDs as the query key. Imagine that I query members 1, 2, and 3. The response is successful, and now I have their data. I want to be able to query only members 1 and 2 (or only member 1) and use the same data as those queried in the first request. How can I do that?
6 Replies
apparent-cyan
apparent-cyan10mo ago
https://tkdodo.eu/blog/mastering-mutations-in-react-query#direct-updates
queryFn: () => {
const members = await fetchMembers();

for (const member of members) {
queryClient.setQueryData(["members", "details", member.id], member)
}
}
queryFn: () => {
const members = await fetchMembers();

for (const member of members) {
queryClient.setQueryData(["members", "details", member.id], member)
}
}
afraid-scarlet
afraid-scarletOP10mo ago
Thanks @ksgn ! With this approach then I'll have .setQueryData for all combinations of members. For instance if I query members 1, 2, and 3, then I'll be storing the individual data for each member, and querying for member 1, 2, or 3 will give me cached data. But if I request for members 2 and 3, it will make a request. Is there any way to avoid this (besides the "brute force" approach of getting all combinations)?
apparent-cyan
apparent-cyan10mo ago
I'm not sure… maybe you could solve it like this?:
// try getting the data from the cache
if (queryClient.getQueryData(["members", "details", id])) {
// use the data
} else {
// fetch the member details
}
// try getting the data from the cache
if (queryClient.getQueryData(["members", "details", id])) {
// use the data
} else {
// fetch the member details
}
other-emerald
other-emerald10mo ago
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
From An unknown user
From An unknown user
other-emerald
other-emerald10mo ago
You may store a full list of members under the ['members'] key and each individual member under the ['members', id]. But if you need a particular slice of the members list, like [2, 3] You need to put them in the key not as an array of ids but as an object {2:true, 3:true} for example. It's a bit silly example but the order of ids inside an object doesn't really matter so 2,3 is the same as 3,2
afraid-scarlet
afraid-scarletOP10mo ago
Thanks for your help @ksgn and @denis.monastyrskyi ! I was able to accomplish what I wanted. Will be closing the post.

Did you find this page helpful?