Open History to see the last commit
1---
2id: MutationCache
3title: MutationCache
4---
5β
6The `MutationCache` is the storage for mutations.
7β
8**Normally, you will not interact with the MutationCache directly and instead use the `QueryClient`.**
9β
10```js
11import { MutationCache } from '@tanstack/react-query'
12β
13const mutationCache = new MutationCache({
14 onError: error => {
15 console.log(error)
16 },
17 onSuccess: data => {
18 console.log(data)
19 },
20})
21```
22β
23Its available methods are:
24β
25- [`getAll`](#mutationcachegetall)
26- [`subscribe`](#mutationcachesubscribe)
27- [`clear`](#mutationcacheclear)
28β
29**Options**
30β
31- `onError?: (error: unknown, variables: unknown, context: unknown, mutation: Mutation) => void`
32 - Optional
33 - This function will be called if some mutation encounters an error.
34- `onSuccess?: (data: unknown, variables: unknown, context: unknown, mutation: Mutation) => void`
35 - Optional
36 - This function will be called if some mutation is successful.
37- `onMutate?: (variables: unknown, mutation: Mutation) => void`
38 - Optional
39 - This function will be called before some mutation executes.
40β
41## Global callbacks
42β
43The `onError`, `onSuccess` 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:
44β
45- `defaultOptions` can be overridden by each Mutation - the global callbacks will **always** be called.
46- `onMutate` does not allow returning a context value.
47β
48## `mutationCache.getAll`
49β
50`getAll` returns all mutations within the cache.
51β
52> Note: This is not typically needed for most applications, but can come in handy when needing more information about a mutation in rare scenarios
53β
54```js
55const mutations = mutationCache.getAll()
56```
57β
58**Returns**
59β
60- `Mutation[]`
61 - Mutation instances from the cache
62β
63## `mutationCache.subscribe`
64β
65The `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.
66β
67```js
68const callback = event => {
69 console.log(event.type, event.mutation)
70}
71β
72const unsubscribe = mutationCache.subscribe(callback)
73```
74β
75**Options**
76β
77- `callback: (mutation?: MutationCacheNotifyEvent) => void`
78 - This function will be called with the mutation cache any time it is updated.
79β
80**Returns**
81β
82- `unsubscribe: Function => void`
83 - This function will unsubscribe the callback from the mutation cache.
84β
85## `mutationCache.clear`
86β
87The `clear` method can be used to clear the cache entirely and start fresh.
88β
89```js
90mutationCache.clear()
91```