Open History to see the last commit
1import { DatePipe } from '@angular/common'
2import { Component, inject } from '@angular/core'
3import { FormsModule } from '@angular/forms'
4import {
5 QueryClient,
6 injectMutation,
7 injectQuery,
8} from '@tanstack/angular-query'
9import { TasksMutations, TasksQueries } from '../services/tasks/queries'
10β
11@Component({
12 selector: 'optimistic-updates',
13 imports: [FormsModule, DatePipe],
14 template: `
15 <p>
16 In this example, new items can be created using a mutation. The new item
17 will be optimistically added to the list in hopes that the server accepts
18 the item. If it does, the list is refetched with the true items from the
19 list. Every now and then, the mutation may fail though. When that happens,
20 the previous list of items is restored and the list is again refetched
21 from the server.
22 </p>
23β
24 <hr />
25 @if (tasks.isLoading()) {
26 <p>Loading...</p>
27 }
28β
29 <div class="container">
30 <label>
31 <input type="checkbox" [(ngModel)]="failMutation" />
32 Fail Mutation
33 </label>
34β
35 <div class="input-container">
36 <input type="text" [(ngModel)]="newItem" placeholder="Enter text" />
37 <button (click)="addItem()">Create</button>
38 <ul>
39 @for (task of tasks.data(); track task) {
40 <li>{{ task }}</li>
41 }
42 </ul>
43β
44 <div>
45 Updated At: {{ tasks.dataUpdatedAt() | date: 'MMMM d, h:mm:ss a ' }}
46 </div>
47 </div>
48 @if (!tasks.isLoading() && tasks.isFetching()) {
49 <p>Fetching in background</p>
50 }
51 </div>
52 `,
53})
54export class OptimisticUpdatesComponent {
55 #queryClient = inject(QueryClient)
56 #tasksQueries = inject(TasksQueries)
57 #tasksMutations = inject(TasksMutations)
58β
59 tasks = injectQuery(() => this.#tasksQueries.list())
60 addMutation = injectMutation(() => ({
61 ...this.#tasksMutations.create(),
62 onSuccess: () => {
63 this.#queryClient.invalidateQueries({
64 queryKey: this.#tasksQueries.list().queryKey,
65 })
66 },
67 onMutate: async ({ task }) => {
68 // Cancel any outgoing refetches
69 // (so they don't overwrite our optimistic update)
70 await this.#queryClient.cancelQueries({
71 queryKey: this.#tasksQueries.list().queryKey,
72 })
73β
74 // Snapshot the previous value
75 const previousTodos = this.#queryClient.getQueryData(
76 this.#tasksQueries.list().queryKey,
77 )
78β
79 // Optimistically update to the new value
80 if (previousTodos) {
81 this.#queryClient.setQueryData(this.#tasksQueries.list().queryKey, [
82 ...previousTodos,
83 task,
84 ])
85 }
86β
87 return previousTodos
88 },
89 onError: (_err, _variables, onMutateResult) => {
90 if (onMutateResult) {
91 this.#queryClient.setQueryData(
92 this.#tasksQueries.list().queryKey,
93 onMutateResult,
94 )
95 }
96 },
97 // Always refetch after error or success:
98 onSettled: () => {
99 this.#queryClient.invalidateQueries({
100 queryKey: this.#tasksQueries.list().queryKey,
101 })
102 },
103 }))
104β
105 newItem = ''
106 failMutation = false
107β
108 addItem() {
109 if (!this.newItem) return
110β
111 this.addMutation.mutate({
112 task: this.newItem,
113 failMutation: this.failMutation,
114 })
115 this.newItem = ''
116 }
117}