Open History to see the last commit
1import { ChangeDetectionStrategy, Component, inject } from '@angular/core'
2import { injectMutation, injectQuery } from '@tanstack/angular-query'
3import { FormsModule } from '@angular/forms'
4import { DatePipe } from '@angular/common'
5import { TasksService } from '../services/tasks.service'
6β
7@Component({
8 changeDetection: ChangeDetectionStrategy.OnPush,
9 selector: 'optimistic-updates',
10 imports: [FormsModule, DatePipe],
11 template: `
12 <p>
13 In this example, new items can be created using a mutation. The new item
14 will be optimistically added to the list in hopes that the server accepts
15 the item. If it does, the list is refetched with the true items from the
16 list. Every now and then, the mutation may fail though. When that happens,
17 the previous list of items is restored and the list is again refetched
18 from the server.
19 </p>
20β
21 <hr />
22 @if (tasks.isLoading()) {
23 <p>Loading...</p>
24 }
25β
26 <div class="container">
27 <label>
28 <input type="checkbox" [(ngModel)]="failMutation" />
29 Fail Mutation
30 </label>
31β
32 <div class="input-container">
33 <input type="text" [(ngModel)]="newItem" placeholder="Enter text" />
34 <button (click)="addItem()">Create</button>
35 <ul>
36 @for (task of tasks.data(); track task) {
37 <li>{{ task }}</li>
38 }
39 </ul>
40β
41 <div>
42 Updated At: {{ tasks.dataUpdatedAt() | date: 'MMMM d, h:mm:ss a ' }}
43 </div>
44 </div>
45 @if (!tasks.isLoading() && tasks.isFetching()) {
46 <p>Fetching in background</p>
47 }
48 </div>
49 `,
50})
51export class OptimisticUpdatesComponent {
52 #tasksService = inject(TasksService)
53β
54 tasks = injectQuery(() => this.#tasksService.allTasks())
55 clearMutation = injectMutation(() => this.#tasksService.addTask())
56 addMutation = injectMutation(() => this.#tasksService.addTask())
57β
58 newItem = ''
59 failMutation = false
60β
61 addItem() {
62 if (!this.newItem) return
63β
64 this.addMutation.mutate({
65 task: this.newItem,
66 failMutation: this.failMutation,
67 })
68 this.newItem = ''
69 }
70}