MutationCache

· abundance's blog


The MutationCache is the storage for mutations.

Normally, you will not interact with the MutationCache directly and instead use the QueryClient.

 1import { MutationCache } from '@tanstack/react-query'
 2
 3const mutationCache = new MutationCache({
 4  onError: (error) => {
 5    console.log(error)
 6  },
 7  onSuccess: (data) => {
 8    console.log(data)
 9  },
10})

Its available methods are:

Options

Global callbacks #

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:

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

1const mutations = mutationCache.getAll()

Returns

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.

1const callback = (event) => {
2  console.log(event.type, event.mutation)
3}
4
5const unsubscribe = mutationCache.subscribe(callback)

Options

Returns

mutationCache.clear #

The clear method can be used to clear the cache entirely and start fresh.

1mutationCache.clear()