T
TanStack3y ago
ambitious-aqua

Reset many queries

Hello, I have queries that are built like the example below:
useQuery(['skills', 'stats'], ...);
useQuery(['badges', 'stats'], ...);
useQuery(['skills', 'stats'], ...);
useQuery(['badges', 'stats'], ...);
I'm trying to refetch all these two queries at once with:
queryClient.refetchQueries({ queryKey: ['stats'], type: 'all' });
queryClient.refetchQueries({ queryKey: ['stats'], type: 'all' });
But it's not working. Did I understand something wrong?
6 Replies
ambitious-aqua
ambitious-aquaOP3y ago
Okay, if I change it to
useQuery(['stats', 'skills'], ...);
useQuery(['stats', 'skills'], ...);
My "refetchQueries" works, is this on purpose? I found this out by looking at: https://github.com/TanStack/query/issues/435
GitHub
queryCache.refetchQueries not working with array keys · Issue #435 ...
There is something wrong with refetchQueries. I'm not able to trigger a refetch on multiple queries, nothing happens, but when called separately everything works fine. This doesn't ...
rare-sapphire
rare-sapphire3y ago
That's intentional. Query keys are best written with an order of specificity. In your case, both queries have to do with stats, so that could come first in their query key arrays. When refetching or invalidating, it will match against any query that starts with the elements in the query key array you pass in. I think Dominik has written about this, I'm trying to find a link
rare-sapphire
rare-sapphire3y ago
Effective React Query Keys
Learn how to structure React Query Keys effectively as your App grows
ambitious-aqua
ambitious-aquaOP3y ago
Wow, this is very interesting! Thank you very much for this, I will study more about it.
rival-black
rival-black3y ago
another tip would be: if you have no hierarchical order, you can use one object for your keys in the first entry of the array, like so:
[{ entity: 'skills', page: 'stats' }]
[{ entity: 'badge', page: 'stats' }]
[{ entity: 'badge', page: 'user' }]
[{ entity: 'skills', page: 'stats' }]
[{ entity: 'badge', page: 'stats' }]
[{ entity: 'badge', page: 'user' }]
with that, you can target everything stats related with:
[{ page: 'stats' }]
[{ page: 'stats' }]
and everything badge related with:
[{ entity: 'badge' }]
[{ entity: 'badge' }]
I've written about that in a follow-up to the above posted article: https://tkdodo.eu/blog/leveraging-the-query-function-context#object-query-keys
Leveraging the Query Function Context
Use what React Query provides for optimal type safety
ambitious-aqua
ambitious-aquaOP3y ago
wow! this is also a very interesting approach, thanks for that! I will put it into practice.

Did you find this page helpful?