框架
版本

useMutationState

useMutationState 是一个 Hook,让你可以访问 MutationCache 中的所有突变。你可以传递 filters 来缩小你的突变范围,并使用 select 来转换突变状态。

示例 1:获取所有正在运行的突变的所有变量

tsx
import { useMutationState } from '@tanstack/react-query'

const variables = useMutationState({
  filters: { status: 'pending' },
  select: (mutation) => mutation.state.variables,
})
import { useMutationState } from '@tanstack/react-query'

const variables = useMutationState({
  filters: { status: 'pending' },
  select: (mutation) => mutation.state.variables,
})

示例 2:通过 mutationKey 获取特定突变的所有数据

tsx
import { useMutation, useMutationState } from '@tanstack/react-query'

const mutationKey = ['posts']

// Some mutation that we want to get the state for
const mutation = useMutation({
  mutationKey,
  mutationFn: (newPost) => {
    return axios.post('/posts', newPost)
  },
})

const data = useMutationState({
  // this mutation key needs to match the mutation key of the given mutation (see above)
  filters: { mutationKey },
  select: (mutation) => mutation.state.data,
})
import { useMutation, useMutationState } from '@tanstack/react-query'

const mutationKey = ['posts']

// Some mutation that we want to get the state for
const mutation = useMutation({
  mutationKey,
  mutationFn: (newPost) => {
    return axios.post('/posts', newPost)
  },
})

const data = useMutationState({
  // this mutation key needs to match the mutation key of the given mutation (see above)
  filters: { mutationKey },
  select: (mutation) => mutation.state.data,
})

示例 3:通过 mutationKey 访问最新的突变数据 每次调用 mutate 都会在突变缓存中为 gcTime 毫秒添加一个新条目。

要访问最新的调用,你可以检查 useMutationState 返回的最后一个条目。

tsx
import { useMutation, useMutationState } from '@tanstack/react-query'

const mutationKey = ['posts']

// Some mutation that we want to get the state for
const mutation = useMutation({
  mutationKey,
  mutationFn: (newPost) => {
    return axios.post('/posts', newPost)
  },
})

const data = useMutationState({
  // this mutation key needs to match the mutation key of the given mutation (see above)
  filters: { mutationKey },
  select: (mutation) => mutation.state.data,
})

// Latest mutation data
const latest = data[data.length - 1]
import { useMutation, useMutationState } from '@tanstack/react-query'

const mutationKey = ['posts']

// Some mutation that we want to get the state for
const mutation = useMutation({
  mutationKey,
  mutationFn: (newPost) => {
    return axios.post('/posts', newPost)
  },
})

const data = useMutationState({
  // this mutation key needs to match the mutation key of the given mutation (see above)
  filters: { mutationKey },
  select: (mutation) => mutation.state.data,
})

// Latest mutation data
const latest = data[data.length - 1]

选项

  • 选项
    • filters?: MutationFilters: 突变过滤器
    • select?: (mutation: Mutation) => TResult
      • 使用此选项来转换突变状态。
  • queryClient?: QueryClient,
    • 使用此选项来使用自定义的 QueryClient。否则,将使用最近上下文中的 QueryClient。

返回值

  • Array<TResult>
    • 将是一个数组,包含 select 为每个匹配的突变返回的值。