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

MutationCache.md

91 lines2.5 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 '@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)
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```