Open History to see the last commit
1import { ChangeDetectionStrategy, Component, inject } from '@angular/core'
2import {
3 injectMutation,
4 injectQuery,
5} from '@tanstack/angular-query-experimental'
6import { FormsModule } from '@angular/forms'
7import { DatePipe } from '@angular/common'
8import { TasksService } from '../services/tasks.service'
9β
10@Component({
11 changeDetection: ChangeDetectionStrategy.OnPush,
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 #tasksService = inject(TasksService)
56β
57 tasks = injectQuery(() => this.#tasksService.allTasks())
58 clearMutation = injectMutation(() => this.#tasksService.addTask())
59 addMutation = injectMutation(() => this.#tasksService.addTask())
60β
61 newItem = ''
62 failMutation = false
63β
64 addItem() {
65 if (!this.newItem) return
66β
67 this.addMutation.mutate({
68 task: this.newItem,
69 failMutation: this.failMutation,
70 })
71 this.newItem = ''
72 }
73}