T
TanStack16mo ago
probable-pink

How to setup automatic invalidation after mutation

I want to setup a remix like automatic invalidation. I saw this post from TkDodo: https://tkdodo.eu/blog/automatic-query-invalidation-after-mutations#the-global-cache-callbacks But I am having trouble understanding how is solution is possible.
const queryClient = new QueryClient({
mutationCache: new MutationCache({
onSuccess: () => {
queryClient.invalidateQueries()
},
}),
})
const queryClient = new QueryClient({
mutationCache: new MutationCache({
onSuccess: () => {
queryClient.invalidateQueries()
},
}),
})
We cannot use queryClient inside its own declaration. Do I need to create a second one above juste to configure correctly the MutationCache ? Thx.
Automatic Query Invalidation after Mutations
Even though there is nothing built into React Query, it doesn't need a lot of code to implement automatic query invalidation in user-land thanks to the global cache callbacks.
2 Replies
sensitive-blue
sensitive-blue16mo ago
You absolutely can use queryClient this way. Have you actually tried it?
ratty-blush
ratty-blush16mo ago
when onSuccess gets invoked, the queryClient is already defined, so this works at runime. If TypeScript is giving you troubles, add an explicit type annotation:
const queryClient: QueryClient = new QueryClient({ ... })
const queryClient: QueryClient = new QueryClient({ ... })
I used to need to do that in previous TS versions, but something must have changed because it's no longer necessary for me.

Did you find this page helpful?