Open History to see the last commit
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.