Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

MutationCache.md

86 lines2.3 KB

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)
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```