Open History to see the last commit
1import { HttpClient } from '@angular/common/http'
2import { Injectable, inject } from '@angular/core'
3import {
4 QueryClient,
5 mutationOptions,
6 queryOptions,
7} from '@tanstack/angular-query-experimental'
8β
9import { lastValueFrom } from 'rxjs'
10β
11@Injectable({
12 providedIn: 'root',
13})
14export class TasksService {
15 #queryClient = inject(QueryClient) // Manages query state and caching
16 #http = inject(HttpClient) // Handles HTTP requests
17β
18 /**
19 * Fetches all tasks from the API.
20 * Returns an observable containing an array of task strings.
21 */
22 allTasks = () =>
23 queryOptions({
24 queryKey: ['tasks'],
25 queryFn: () => {
26 return lastValueFrom(this.#http.get<Array<string>>('/api/tasks'))
27 },
28 })
29β
30 /**
31 * Creates a mutation for adding a task.
32 * On success, invalidates and refetches the "tasks" query cache to update the task list.
33 */
34 addTask() {
35 return mutationOptions({
36 mutationFn: ({
37 task,
38 failMutation = false,
39 }: {
40 task: string
41 failMutation: boolean
42 }) =>
43 lastValueFrom(
44 this.#http.post(
45 `/api/tasks${failMutation ? '-wrong-url' : ''}`,
46 task,
47 ),
48 ),
49 mutationKey: ['tasks'],
50 onSuccess: () => {
51 this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
52 },
53 onMutate: async ({ task }) => {
54 // Cancel any outgoing refetches
55 // (so they don't overwrite our optimistic update)
56 await this.#queryClient.cancelQueries({ queryKey: ['tasks'] })
57β
58 // Snapshot the previous value
59 const previousTodos = this.#queryClient.getQueryData<Array<string>>([
60 'tasks',
61 ])
62β
63 // Optimistically update to the new value
64 if (previousTodos) {
65 this.#queryClient.setQueryData<Array<string>>(
66 ['tasks'],
67 [...previousTodos, task],
68 )
69 }
70β
71 return previousTodos
72 },
73 onError: (err, variables, context) => {
74 if (context) {
75 this.#queryClient.setQueryData<Array<string>>(['tasks'], context)
76 }
77 },
78 // Always refetch after error or success:
79 onSettled: () => {
80 this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
81 },
82 })
83 }
84}