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