The MutationCache
is the storage for mutations.
Normally, you will not interact with the MutationCache directly and instead use the QueryClient
.
import { MutationCache } from '@tanstack/react-query'
const mutationCache = new MutationCache({ onError: error => { console.log(error) }, onSuccess: data => { console.log(data) },})
Its available methods are:
Options
onError?: (error: unknown, variables: unknown, context: unknown, mutation: Mutation) => Promise<unknown> | unknown
onSuccess?: (data: unknown, variables: unknown, context: unknown, mutation: Mutation) => Promise<unknown> | unknown
onSettled?: (data: unknown | undefined, error: unknown | null, variables: unknown, context: unknown, mutation: Mutation) => Promise<unknown> | unknown
onMutate?: (variables: unknown, mutation: Mutation) => Promise<unknown> | unknown
The onError
, onSuccess
, onSettled
and onMutate
callbacks on the MutationCache can be used to handle these events on a global level. They are different to defaultOptions
provided to the QueryClient because:
defaultOptions
can be overridden by each Mutation - the global callbacks will always be called.onMutate
does not allow returning a context value.mutationCache.getAll
getAll
returns all mutations within the cache.
Note: This is not typically needed for most applications, but can come in handy when needing more information about a mutation in rare scenarios
const mutations = mutationCache.getAll()
Returns
Mutation[]
mutationCache.subscribe
The subscribe
method can be used to subscribe to the mutation cache as a whole and be informed of safe/known updates to the cache like mutation states changing or mutations being updated, added or removed.
const callback = event => { console.log(event.type, event.mutation)}
const unsubscribe = mutationCache.subscribe(callback)
Options
callback: (mutation?: MutationCacheNotifyEvent) => void
Returns
unsubscribe: Function => void
mutationCache.clear
The clear
method can be used to clear the cache entirely and start fresh.
mutationCache.clear()
Fast track your learning and
take the offical React Query course ↗️
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.