来自修改的失效处理
使查询失效只是问题的一半;知道何时使其失效则是另一半。通常,当应用中的某个修改成功执行后,你的应用中很可能存在若干相关查询需要被使其失效,甚至可能需要重新拉取,以反映该修改带来的新变更。
例如,假设我们有一个用于发布新待办事项的修改:
TypeScript
1postTodoMutation = injectMutation(() => ({2 mutationFn: postTodo,3}))当一个成功的 postTodo 修改发生时,你很可能希望所有 todos 查询都被使其失效,并可能重新拉取,以展示新的待办事项条目。为此,你可以使用 injectMutation 的 onSuccess 选项以及 client 的 invalidateQueries 函数:
TypeScript
1import {2 injectMutation,3 QueryClient,4} from '@tanstack/angular-query-experimental'5 6export class TodosComponent {7 readonly queryClient = inject(QueryClient)8 9 // When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key10 readonly addTodoMutation = injectMutation(() => ({11 mutationFn: addTodo,12 onSuccess: () => {13 this.queryClient.invalidateQueries({ queryKey: ['todos'] })14 this.queryClient.invalidateQueries({ queryKey: ['reminders'] })15 },16 }))17}在 onSuccess 中返回一个 Promise 可确保数据更新完成之后,修改才被视为完全结束(即:isPending 保持为 true,直至 onSuccess 被兑现)。
你可以利用 injectMutation 函数 提供的任意回调来触发你的失效处理逻辑。
延伸阅读
如需了解如何在修改后自动使查询失效的技术,请参阅 TkDodo 关于“修改后自动使查询失效”的文章。
你可以利用 injectMutation 函数 提供的任意回调来触发你的失效处理逻辑。