使查询失效只是战役的一半。知道何时使它们失效是另一半。通常,当应用程序中的 mutation 成功时,很可能应用程序中存在相关的查询需要失效,并可能需要重新获取以考虑 mutation 带来的新更改。
例如,假设我们有一个 mutation 来发布新的 todo
mutation = injectMutation(() => ({
mutationFn: postTodo,
}))
mutation = injectMutation(() => ({
mutationFn: postTodo,
}))
当成功的 postTodo mutation 发生时,我们可能希望所有 todos 查询都失效,并可能重新获取以显示新的 todo 项。为此,您可以使用 injectMutation 的 onSuccess 选项和 client 的 invalidateQueries 函数
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'] })
},
}))
}
您可以使用 injectMutation 函数中提供的任何回调来连接失效操作