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

useMutationState.md

81 lines2.3 KB

1---
2id: useMutationState
3title: useMutationState
4---
5​
6`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass `filters` to it to narrow down your mutations, and `select` to transform the mutation state.
7​
8**Example 1: Get all variables of all running mutations**
9​
10```tsx
11import { useMutationState } from '@tanstack/react-query'
12​
13const variables = useMutationState({
14 filters: { status: 'pending' },
15 select: (mutation) => mutation.state.variables,
16})
17```
18​
19**Example 2: Get all data for specific mutations via the `mutationKey`**
20​
21```tsx
22import { useMutation, useMutationState } from '@tanstack/react-query'
23​
24const mutationKey = ['posts']
25​
26// Some mutation that we want to get the state for
27const mutation = useMutation({
28 mutationKey,
29 mutationFn: (newPost) => {
30 return axios.post('/posts', newPost)
31 },
32})
33​
34const data = useMutationState({
35 // this mutation key needs to match the mutation key of the given mutation (see above)
36 filters: { mutationKey },
37 select: (mutation) => mutation.state.data,
38})
39```
40​
41**Example 3: Access the latest mutation data via the `mutationKey`**
42Each invocation of `mutate` adds a new entry to the mutation cache for `gcTime` milliseconds.
43​
44To access the latest invocation, you can check for the last item that `useMutationState` returns.
45​
46```tsx
47import { useMutation, useMutationState } from '@tanstack/react-query'
48​
49const mutationKey = ['posts']
50​
51// Some mutation that we want to get the state for
52const mutation = useMutation({
53 mutationKey,
54 mutationFn: (newPost) => {
55 return axios.post('/posts', newPost)
56 },
57})
58​
59const data = useMutationState({
60 // this mutation key needs to match the mutation key of the given mutation (see above)
61 filters: { mutationKey },
62 select: (mutation) => mutation.state.data,
63})
64​
65// Latest mutation data
66const latest = data[data.length - 1]
67```
68​
69**Options**
70​
71- `options`
72 - `filters?: MutationFilters`: [Mutation Filters](../../guides/filters#mutation-filters)
73 - `select?: (mutation: Mutation) => TResult`
74 - Use this to transform the mutation state.
75- `queryClient?: QueryClient`,
76 - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
77​
78**Returns**
79​
80- `Array<TResult>`
81 - Will be an Array of whatever `select` returns for each matching mutation.