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•10mo ago
afraid-scarletOP•10mo 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•10mo ago
I'm not sure… maybe you could solve it like this?:
other-emerald•10mo ago
Your problem is the list of ids as a key.https://tanstack.com/query/v4/docs/framework/react/guides/query-keys#query-keys-are-hashed-deterministically
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.

other-emerald•10mo 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-scarletOP•10mo ago
Thanks for your help @ksgn and @denis.monastyrskyi ! I was able to accomplish what I wanted. Will be closing the post.