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

useMutationState.md

53 lines1.5 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**Options**
42​
43- `options`
44 - `filters?: MutationFilters`: [Mutation Filters](./guides/filters#mutation-filters)
45 - `select?: (mutation: Mutation) => TResult`
46 - Use this to transform the mutation state.
47- `queryClient?: QueryClient`,
48 - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
49​
50**Returns**
51​
52- `Array<TResult>`
53 - Will be an Array of whatever `select` returns for each matching mutation.