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 '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β
38## Global callbacks
39β
40The `onError` and `onSuccess` 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:
41- `defaultOptions` can be overridden by each Mutation - the global callbacks will **always** be called.
42β
43## `mutationCache.getAll`
44β
45`getAll` returns all mutations within the cache.
46β
47> Note: This is not typically needed for most applications, but can come in handy when needing more information about a mutation in rare scenarios
48β
49```js
50const mutations = mutationCache.getAll()
51```
52β
53**Returns**
54β
55- `Mutation[]`
56 - Mutation instances from the cache
57β
58## `mutationCache.subscribe`
59β
60The `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.
61β
62```js
63const callback = mutation => {
64 console.log(mutation)
65}
66β
67const unsubscribe = mutationCache.subscribe(callback)
68```
69β
70**Options**
71β
72- `callback: (mutation?: Mutation) => void`
73 - This function will be called with the mutation cache any time it is updated.
74β
75**Returns**
76β
77- `unsubscribe: Function => void`
78 - This function will unsubscribe the callback from the mutation cache.
79β
80## `mutationCache.clear`
81β
82The `clear` method can be used to clear the cache entirely and start fresh.
83β
84```js
85mutationCache.clear()
86```