useMutationState 是一个钩子,它允许您访问 MutationCache 中的所有 mutation。您可以向其传递 filters 来缩小 mutation 的范围,并使用 select 来转换 mutation 状态。
示例 1:获取所有正在运行的 mutations 的所有变量
import { useMutationState } from '@tanstack/solid-query'
const variables = useMutationState(() => {
filters: { status: 'pending' },
select: (mutation) => mutation.state.variables,
})
import { useMutationState } from '@tanstack/solid-query'
const variables = useMutationState(() => {
filters: { status: 'pending' },
select: (mutation) => mutation.state.variables,
})
示例 2:通过 mutationKey 获取特定 mutations 的所有数据
import { useMutation, useMutationState } from '@tanstack/solid-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/solid-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 访问最新的 mutation 数据。每次调用 mutate 都会为 gcTime 毫秒在 mutation 缓存中添加一个新条目。
要访问最新的调用,你可以检查 useMutationState 返回的最后一个条目。
import { useMutation, useMutationState } from '@tanstack/solid-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/solid-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]
选项
Returns (返回)