使查询无效只是战斗的一半。知道何时使它们无效是另一半。通常,当您的应用程序中的 mutation 成功时,它很可能是您应用程序中相关的查询需要被使之无效,并可能重新获取以考虑来自 mutation 的新更改。
例如,假设我们有一个用于发布新 todo 的 mutation
mutation = injectMutation(() => ({
mutationFn: postTodo,
}))
mutation = injectMutation(() => ({
mutationFn: postTodo,
}))
当成功的 postTodo mutation 发生时,我们可能希望所有 todos 查询都被使之无效,并可能重新获取以显示新的 todo 项。要做到这一点,您可以使用 injectMutation 的 onSuccess 选项和 client 的 invalidateQueries 函数。
import { injectMutation, useQueryClient } from '@tanstack/react-query'
const queryClient = useQueryClient()
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const mutation = injectMutation({
mutationFn: addTodo,
onSuccess: async () => {
// If you're invalidating a single query
await queryClient.invalidateQueries({ queryKey: ['todos'] })
// If you're invalidating multiple queries
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['todos'] }),
queryClient.invalidateQueries({ queryKey: ['reminders'] }),
])
},
})
import { injectMutation, useQueryClient } from '@tanstack/react-query'
const queryClient = useQueryClient()
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const mutation = injectMutation({
mutationFn: addTodo,
onSuccess: async () => {
// If you're invalidating a single query
await queryClient.invalidateQueries({ queryKey: ['todos'] })
// If you're invalidating multiple queries
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['todos'] }),
queryClient.invalidateQueries({ queryKey: ['reminders'] }),
])
},
})
在 onSuccess 上返回一个 Promise 确保数据在 mutation 完全完成之前更新(即,直到 onSuccess 完成,isPending 才为 true)
import {
injectMutation,
QueryClient,
} from '@tanstack/angular-query-experimental'
export class TodosComponent {
queryClient = inject(QueryClient)
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
mutation = injectMutation(() => ({
mutationFn: addTodo,
onSuccess: () => {
this.queryClient.invalidateQueries({ queryKey: ['todos'] })
this.queryClient.invalidateQueries({ queryKey: ['reminders'] })
},
}))
}
import {
injectMutation,
QueryClient,
} from '@tanstack/angular-query-experimental'
export class TodosComponent {
queryClient = inject(QueryClient)
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
mutation = injectMutation(() => ({
mutationFn: addTodo,
onSuccess: () => {
this.queryClient.invalidateQueries({ queryKey: ['todos'] })
this.queryClient.invalidateQueries({ queryKey: ['reminders'] })
},
}))
}
有关使查询在 mutations 之后自动无效的技术,请参阅社区资源中的 Mutations 后自动查询无效化。