Understanding Query Key Objects
I just started using react-query and see most examples with simple query keys containing a single value.
Let's say I have the following:
Then if I want to fetch all squares that are either
blue OR red would I do
does this store all color combinations in their own query?
And is this the same if I have more filters?
8 Replies
absent-sapphire•11mo ago
This is a good read: https://tkdodo.eu/blog/effective-react-query-keys
Effective React Query Keys
Learn how to structure React Query Keys effectively as your App grows
sensitive-blueOP•11mo ago
I read that twice before posting this lol. It seems like that example can only be filtered by
all | open | done but not multiple, which wouldn't really make sense in that context.
Which would also be a single string and not an objectabsent-sapphire•11mo ago
It's really up to you. If you have
{ blue: true, red: true } and that's part of your queryKey and used in your fetch, then you'll have a cache entry of blue and red squares.
If you just do { red: true} then you'll have a cache entry of just red squares. Are you using the devtools? Seeing the cache entries there is pretty helpful in understanding how things worksensitive-blueOP•11mo ago
I'm currently working with an unstable react native refactor so dev tools wan't something I looked into 😅 I suppose I could spin up a dummy app to test this stuff.
Your answer makes sense though, thanks! 🙂
And to invalidate the cache I would just need to pass
['square', {red: true}] for it to catch all objects with red: true?absent-sapphire•11mo ago
There's multiple ways to invalidate, but if that matches your key then yes.
QueryFilters has quite a bit of functionality
https://tanstack.com/query/v5/docs/reference/QueryClient/#queryclientinvalidatequeries
https://tanstack.com/query/v5/docs/framework/react/guides/filters#query-filtersQueryClient | TanStack Query Docs
QueryClient The QueryClient can be used to interact with a cache: tsx import { QueryClient } from '@tanstack/react-query' const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime:...
Filters | TanStack Query React Docs
Some methods within TanStack Query accept a QueryFilters or MutationFilters object. Query Filters A query filter is an object with certain conditions to match a query with: tsx // Cancel all queries a...
absent-sapphire•11mo ago
Fuzzy matching, exact matching, predicate, etc
extended-salmon•11mo ago
You usually do not want to only invalidate 1 single query, when you get to invalidation, you invalidate everything. But as troywoy explained above, you can match all squares first using
['square'] then you'd use the predicate to filter them using a function.sensitive-blueOP•11mo ago
Ah that makes much more sense, thanks!