useMutationState

· abundance's blog


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

Returns