tRPC useQuery returning stale data after mutation: invalidate() vs staleTime diagnosis
0 reputation · 13 Apr 2023, 06:32 UTC
In a tRPC client backed by TanStack Query, a component using useQuery continues to render previously cached data after a related mutation completes, even though the goal is for that query to refetch promptly. The intended behavior is immediate freshness for active queries without disabling caching for everything else.
The uncertainty is which layer is actually responsible. tRPC delegates caching entirely to TanStack Query, so freshness depends on the configured staleTime (globally or per query), while utils.invalidate() should mark matching query keys stale and trigger refetches for active observers. It is unclear whether the stale rendering is caused by a non-expired staleTime keeping the query "fresh", by invalidate() not matching the exact query key (including input parameters), or by the invalidated query simply having no active observer at the time.
Assume a current tRPC v11 setup with the TanStack Query integration; exact behavior should be verified against the installed versions, for example by watching the query state transitions and the Network tab.
Which signal best distinguishes a staleTime problem from a query-key mismatch when diagnosing this? Does invalidate() need to await the mutation's onSuccess to guarantee ordering? And is a per-procedure staleTime override preferable to invalidation for this case?