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.
Example 1: Get all variables of all running mutations
1import { useMutationState } from '@tanstack/react-query'
2
3const variables = useMutationState({
4 filters: { status: 'pending' },
5 select: (mutation) => mutation.state.variables,
6})
Example 2: Get all data for specific mutations via the mutationKey
1import { useMutation, useMutationState } from '@tanstack/react-query'
2
3const mutationKey = ['posts']
4
5// Some mutation that we want to get the state for
6const mutation = useMutation({
7 mutationKey,
8 mutationFn: (newPost) => {
9 return axios.post('/posts', newPost)
10 },
11})
12
13const data = useMutationState({
14 // this mutation key needs to match the mutation key of the given mutation (see above)
15 filters: { mutationKey },
16 select: (mutation) => mutation.state.data,
17})
Example 3: Access the latest mutation data via the mutationKey
Each invocation of mutate adds a new entry to the mutation cache for gcTime milliseconds.
To access the latest invocation, you can check for the last item that useMutationState returns.
1import { useMutation, useMutationState } from '@tanstack/react-query'
2
3const mutationKey = ['posts']
4
5// Some mutation that we want to get the state for
6const mutation = useMutation({
7 mutationKey,
8 mutationFn: (newPost) => {
9 return axios.post('/posts', newPost)
10 },
11})
12
13const data = useMutationState({
14 // this mutation key needs to match the mutation key of the given mutation (see above)
15 filters: { mutationKey },
16 select: (mutation) => mutation.state.data,
17})
18
19// Latest mutation data
20const latest = data[data.length - 1]
Options
optionsfilters?: MutationFilters: Mutation Filtersselect?: (mutation: Mutation) => TResult- Use this to transform the mutation state.
queryClient?: QueryClient,- Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
Returns
Array<TResult>- Will be an Array of whatever
selectreturns for each matching mutation.
- Will be an Array of whatever
last updated: