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