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

MutationCache.md

75 lines1.7 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})
18```
19​
20Its available methods are:
21​
22- [`getAll`](#mutationcachegetall)
23- [`subscribe`](#mutationcachesubscribe)
24- [`clear`](#mutationcacheclear)
25​
26**Options**
27​
28- `onError?: (error: unknown, variables: unknown, context: unknown, mutation: Mutation) => void`
29 - Optional
30 - This function will be called if some mutation encounters an error.
31​
32## `mutationCache.getAll`
33​
34`getAll` returns all mutations within the cache.
35​
36> Note: This is not typically needed for most applications, but can come in handy when needing more information about a mutation in rare scenarios
37​
38```js
39const mutations = mutationCache.getAll()
40```
41​
42**Returns**
43​
44- `Mutation[]`
45 - Mutation instances from the cache
46​
47## `mutationCache.subscribe`
48​
49The `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.
50​
51```js
52const callback = mutation => {
53 console.log(mutation)
55​
56const unsubscribe = mutationCache.subscribe(callback)
57```
58​
59**Options**
60​
61- `callback: (mutation?: Mutation) => void`
62 - This function will be called with the mutation cache any time it is updated.
63​
64**Returns**
65​
66- `unsubscribe: Function => void`
67 - This function will unsubscribe the callback from the mutation cache.
68​
69## `mutationCache.clear`
70​
71The `clear` method can be used to clear the cache entirely and start fresh.
72​
73```js
74mutationCache.clear()
75```