Repository navigation
Closed
Labels
Description
Background
TanStack Query provides invalidateQueries to refresh multiple queries by pattern matching. Currently, query-db-collection only supports manual refetch per collection. This requires developers to import and call refetch on each related collection manually.
Problem
When using multiple query collections, invalidating related queries requires boilerplate:
// Current approach - manual coordination
await Promise.all([
todoCollection.utils.refetch(),
userStatsCollection.utils.refetch(),
projectSummaryCollection.utils.refetch()
])Proposed Solution
Add invalidation support specifically to query-db-collection by:
- Allowing collections to subscribe to invalidation events
- Pattern matching against the collection's queryKey
- Automatically calling refetch when matched
Implementation
// Add to query-db-collection
export interface QueryCollectionConfig<TItem, TError, TQueryKey> {
// ... existing options ...
}
// In queryCollectionOptions implementation
const observerOptions = {
// ... existing options ...
// Subscribe to invalidation events
onInvalidate: () => {
// This is called by TanStack Query when invalidateQueries matches
refetch()
}
}
// The queryClient.invalidateQueries will work automatically
queryClient.invalidateQueries({ queryKey: ['todos'] })
// All collections with queryKey starting with ['todos'] will refetchUsage Example
// Define collections
const todoCollection = createCollection(
queryCollectionOptions({
queryKey: ['todos', userId],
queryFn: fetchTodos,
getKey: (item) => item.id,
queryClient,
})
)
const todoStatsCollection = createCollection(
queryCollectionOptions({
queryKey: ['todos', 'stats', userId],
queryFn: fetchTodoStats,
getKey: (item) => item.id,
queryClient,
})
)
// Later, invalidate all todo-related queries
await queryClient.invalidateQueries({
queryKey: ['todos'] // Matches both collections
})Benefits
- Works with existing TanStack Query invalidation patterns
- No new APIs to learn
- Leverages QueryClient's pattern matching
- Each collection manages its own invalidation response
Reacted by Jaedyn
Activity
kels-c commentedon Aug 2, 2025
Hi @KyleAMathews, can I pick this up?
KyleAMathews commentedon Aug 2, 2025
Yes please!
kels-c commentedon Aug 5, 2025
Hi @KyleAMathews, I have a few question, just to make sure I'm tracking the request correctly! I've used query as an end user, and I'm learning the internals as I go.
After reading through some of the code in queryCache, I think we'd like to use the
getQueryCachefrom the client, call thesubscribemethod, and listen for the 'updated' events, and check if the state of a query is invalidated. Am I on the right track?Is there a there a utility for this that exists? Want to make sure I'm not duplicating any logic.
Also, for the implementation section, I noticed there's a
onInvalidatecallback in the example. IMHO, I think we want to handlerefetchinternally, and not expose that callback andrefetchmethod.Thanks!
KyleAMathews commentedon Aug 5, 2025
👋
I'm not actually an expert on TanStack Query so you'll need to dig a bit to verify things but this is what chatgpt came up:
1. Subscribing to invalidation events
Yes – that’s exactly the hook-point TanStack Query exposes.
queryClient.getQueryCache().subscribe(cb)gives you a QueryCacheNotifyEvent. For invalidation you care about:When
queryClient.invalidateQueries(...)runs, every affected query emits one of thoseupdatedevents andquery.state.isInvalidatedflips totrue. A minimal listener in the collection looks like:unsubscribeand call it from the collection’sonDisposeso we don’t leak listeners.2. Pattern‑matching the
queryKeyYup. TanStack exports
partialDeepEqual(and, starting with 5.30,partialMatchKey) from@tanstack/query-core.Both implement the same “prefix‑match” semantics that
invalidateQueriesalready uses, so there’s no need to duplicate that logic.3. Why we don’t need a public
onInvalidateI agree with your instinct to not surface another callback. Collections already expose
utils.refetch(), and the behavior we want is “whenever someone invalidates a matching key, transparently refetch”.So inside queryCollectionOptions we:
setup.observer.refetch()(same thing the user would call) when a match fires.cleanup.That keeps the external API unchanged – users still call the idiomatic:
…and every collection whose key partially matches
[ 'todos' ]will self‑refresh automatically. No new surface area to learn.4. Edge cases & foot‑guns
utils.refetch()behaviour developers already rely on.QueryClientwill de‑dupe the network requests; we just funnel a singlerefetch()call per event, so no extra risk.KyleAMathews commentedon Jul 21, 2026
Completed by the native TanStack Query invalidation behavior already present in the adapter and locked down by the behavior matrix in #1655. Applications should call queryClient.invalidateQueries directly; Query remains the matching and invalidation authority, so no collection-specific invalidation API is needed. See the final outcome in RFC #1643.