修改
与查询不同,修改通常用于创建/更新/删除数据或执行服务端副作用。为此,TanStack Query 导出了一个 injectMutation 函数。
以下是一个将新待办事项添加到服务端的修改示例:
1@Component({2 template: `3 <div>4 @if (createTodoMutation.isPending()) {5 <span>Adding todo...</span>6 } @else if (createTodoMutation.isError()) {7 <div>An error occurred: {{ createTodoMutation.error()?.message }}</div>8 } @else if (createTodoMutation.isSuccess()) {9 <div>Todo added!</div>10 }11 <button (click)="createTodoMutation.mutate(1)">Create Todo</button>12 </div>13 `,14})15export class TodosComponent {16 readonly todoService = inject(TodoService)17 readonly createTodoMutation = injectMutation(() => ({18 mutationFn: (todoId: number) =>19 lastValueFrom(this.todoService.create(todoId)),20 }))21}在任意时刻,一个修改只能处于以下状态之一:
isIdle或status === 'idle'— 修改当前处于空闲状态,或处于全新/重置状态isPending或status === 'pending'— 修改当前正在运行isError或status === 'error'— 修改遇到了错误isSuccess或status === 'success'— 修改成功完成,且修改数据可用
除上述主要状态外,根据修改所处的具体状态,还可获取更多相关信息:
error— 若修改处于error状态,则可通过error属性获取错误信息。data— 若修改处于success状态,则可通过data属性获取数据。
在上面的示例中,你还看到:可通过向 mutate 函数传入单个变量或对象,将变量传递给你的修改函数。
即使仅使用变量,修改本身也并不特别;但当配合 onSuccess 选项、Query Client 的 invalidateQueries 方法 和 Query Client 的 setQueryData 方法 使用时,修改便成为一种非常强大的工具。
重置修改状态
有时你需要清除某次修改请求的 error 或 data。为此,可使用 reset 函数来处理:
1@Component({2 selector: 'todo-item',3 imports: [ReactiveFormsModule],4 template: `5 <form [formGroup]="todoForm" (ngSubmit)="onCreateTodo()">6 @if (createTodoMutation.error()) {7 <h5 (click)="createTodoMutation.reset()">8 {{ createTodoMutation.error() }}9 </h5>10 }11 <input type="text" formControlName="title" />12 <br />13 <button type="submit">Create Todo</button>14 </form>15 `,16})17export class TodosComponent {18 readonly createTodoMutation = injectMutation(() => ({19 mutationFn: createTodo,20 }))21 22 readonly fb = inject(NonNullableFormBuilder)23 24 todoForm = this.fb.group({25 title: this.fb.control('', {26 validators: [Validators.required],27 }),28 })29 30 title = toSignal(this.todoForm.controls.title.valueChanges, {31 initialValue: '',32 })33 34 onCreateTodo = () => {35 this.createTodoMutation.mutate(this.title())36 }37}修改副作用
injectMutation 提供了一些辅助选项,允许你在修改生命周期的任一阶段快速、便捷地执行副作用。这些选项既适用于 修改后使查询失效并重新拉取,也适用于 乐观更新。
1addTodoMutation = injectMutation(() => ({2 mutationFn: addTodo,3 onMutate: (variables, context) => {4 // A mutation is about to happen!5 6 // Optionally return a result containing data to use when for example rolling back7 return { id: 1 }8 },9 onError: (error, variables, onMutateResult, context) => {10 // An error happened!11 console.log(`rolling back optimistic update with id ${onMutateResult.id}`)12 },13 onSuccess: (data, variables, onMutateResult, context) => {14 // Boom baby!15 },16 onSettled: (data, error, variables, onMutateResult, context) => {17 // Error or success... doesn't matter!18 },19}))若在任一回调函数中返回 Promise,则该 Promise 将先被 await,然后才会调用下一个回调:
1addTodoMutation = injectMutation(() => ({2 mutationFn: addTodo,3 onSuccess: async () => {4 console.log("I'm first!")5 },6 onSettled: async () => {7 console.log("I'm second!")8 },9}))你可能会希望在调用 mutate 时,触发超出 injectMutation 上定义的回调之外的额外回调。这可用于触发组件特定的副作用。为此,你可在修改变量之后,向 mutate 函数传入任意相同的回调选项。支持的选项包括:onSuccess、onError 和 onSettled。请注意:若组件在修改完成之前即被销毁,则这些额外回调将不会执行。
1addTodoMutation = injectMutation(() => ({2 mutationFn: addTodo,3 onSuccess: (data, variables, onMutateResult, context) => {4 // I will fire first5 },6 onError: (error, variables, onMutateResult, context) => {7 // I will fire first8 },9 onSettled: (data, error, variables, onMutateResult, context) => {10 // I will fire first11 },12}))13 14addTodoMutation.mutate(todo, {15 onSuccess: (data, variables, onMutateResult, context) => {16 // I will fire second!17 },18 onError: (error, variables, onMutateResult, context) => {19 // I will fire second!20 },21 onSettled: (data, error, variables, onMutateResult, context) => {22 // I will fire second!23 },24})连续修改
在处理连续修改时,onSuccess、onError 和 onSettled 回调的行为略有不同。当这些回调作为参数传给 mutate 函数时,它们仅触发一次,且仅当组件仍处于活跃状态时才触发。这是因为每次调用 mutate 函数时,修改观察者(mutation observer)都会被移除并重新订阅。相反,injectMutation 上定义的处理器会对每一次 mutate 调用都执行。
请注意:传给
injectMutation的mutationFn很可能为异步函数。此时,修改实际完成的顺序可能与mutate函数调用的顺序不一致。
1export class Example {2 readonly addTodoMutation = injectMutation(() => ({3 mutationFn: addTodo,4 onSuccess: (data, variables, onMutateResult, context) => {5 // Will be called 3 times6 },7 }))8 9 doMutations() {10 ;['Todo 1', 'Todo 2', 'Todo 3'].forEach((todo) => {11 this.addTodoMutation.mutate(todo, {12 onSuccess: (data, variables, onMutateResult, context) => {13 // Will execute only once, for the last mutation (Todo 3),14 // regardless which mutation resolves first15 },16 })17 })18 }19}Promise
请使用 mutateAsync 替代 mutate,以获取一个 Promise:它将在成功时解析,在出错时抛出异常。例如,这可用于组合副作用。
1addTodoMutation = injectMutation(() => ({ mutationFn: addTodo }))2 3try {4 const todo = await addTodoMutation.mutateAsync(todo)5 console.log(todo)6} catch (error) {7 console.error(error)8} finally {9 console.log('done')10}重试
默认情况下,TanStack Query 不会在修改出错时自动重试;但可通过 retry 选项启用重试:
1addTodoMutation = injectMutation(() => ({2 mutationFn: addTodo,3 retry: 3,4}))若因设备离线导致修改失败,则当设备重新联网后,这些修改将按原有顺序重试。
持久化修改
如有需要,修改可持久化至存储并在后续恢复。这可通过注水(hydration)函数实现:
1const queryClient = new QueryClient()2 3// Define the "addTodo" mutation4queryClient.setMutationDefaults(['addTodo'], {5 mutationFn: addTodo,6 onMutate: async (variables, context) => {7 // Cancel current queries for the todos list8 await context.client.cancelQueries({ queryKey: ['todos'] })9 10 // Create optimistic todo11 const optimisticTodo = { id: uuid(), title: variables.title }12 13 // Add optimistic todo to todos list14 context.client.setQueryData(['todos'], (old) => [...old, optimisticTodo])15 16 // Return result with the optimistic todo17 return { optimisticTodo }18 },19 onSuccess: (result, variables, onMutateResult, context) => {20 // Replace optimistic todo in the todos list with the result21 context.client.setQueryData(['todos'], (old) =>22 old.map((todo) =>23 todo.id === onMutateResult.optimisticTodo.id ? result : todo,24 ),25 )26 },27 onError: (error, variables, onMutateResult, context) => {28 // Remove optimistic todo from the todos list29 context.client.setQueryData(['todos'], (old) =>30 old.filter((todo) => todo.id !== onMutateResult.optimisticTodo.id),31 )32 },33 retry: 3,34})35 36class someComponent {37 // Start mutation in some component:38 readonly addTodoMutation = injectMutation(() => ({39 mutationKey: ['addTodo'],40 }))41 42 someMethod() {43 addTodoMutation.mutate({ title: 'title' })44 }45}46 47// If the mutation has been paused because the device is for example offline,48// Then the paused mutation can be dehydrated when the application quits:49const state = dehydrate(queryClient)50 51// The mutation can then be hydrated again when the application is started:52hydrate(queryClient, state)53 54// Resume the paused mutations:55queryClient.resumePausedMutations()离线修改的持久化
若你使用 persistQueryClient 插件 持久化离线修改,则页面重载后无法恢复这些修改,除非你提供默认的修改函数。
这是一个技术限制:在外部存储中持久化时,仅会保存修改的状态,而函数无法被序列化。注水(hydration)后,触发修改的组件可能尚未初始化,因此调用 resumePausedMutations 可能引发错误:No mutationFn found。
修改作用域
默认情况下,所有修改均并行执行——即使你多次调用同一修改的 .mutate()。可通过为修改指定 scope 并配合 id 来避免这种情况。所有具有相同 scope.id 的修改将串行执行,这意味着:当它们被触发时,若已有同作用域的修改正在进行,则新修改将进入 isPaused: true 状态;它们会被加入队列,并在其轮到执行时自动恢复。
1const mutation = injectMutation({2 mutationFn: addTodo,3 scope: {4 id: 'todo',5 },6})