Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

quick-start.md

99 lines2.2 KB

1---
2id: quick-start
3title: Quick Start
4---
5​
6[//]: # 'Example'
7​
8If you're looking for a fully functioning example, please have a look at our [basic codesandbox example](./examples/basic)
9​
10### Configure the QueryClient
11​
12Pass a factory to `provideTanStackQuery`. Angular runs it once per injector and in an injection context, so it can use `inject()`.
13​
14```ts
15import { provideHttpClient } from '@angular/common/http'
16import { bootstrapApplication } from '@angular/platform-browser'
17import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
18​
19bootstrapApplication(AppComponent, {
20 providers: [
21 provideHttpClient(),
22 provideTanStackQuery(() => new QueryClient()),
23 ],
24})
25```
26​
27### Component with query and mutation
28​
29```angular-ts
30import { HttpClient } from '@angular/common/http'
31import { Component, Injectable, inject } from '@angular/core'
32import {
33 injectMutation,
34 injectQuery,
35 QueryClient,
36} from '@tanstack/angular-query'
37import { lastValueFrom } from 'rxjs'
38​
39@Component({
40 template: `
41 <div>
42 <button (click)="onAddTodo()">Add Todo</button>
43​
44 <ul>
45 @for (todo of todosQuery.data(); track todo.title) {
46 <li>{{ todo.title }}</li>
47 }
48 </ul>
49 </div>
50 `,
51})
52export class TodosComponent {
53 readonly todoService = inject(TodoService)
54 readonly queryClient = inject(QueryClient)
55​
56 readonly todosQuery = injectQuery(() => ({
57 queryKey: ['todos'],
58 queryFn: () => this.todoService.getTodos(),
59 }))
60​
61 readonly addTodoMutation = injectMutation(() => ({
62 mutationFn: (todo: Todo) => this.todoService.addTodo(todo),
63 onSuccess: () => {
64 this.queryClient.invalidateQueries({ queryKey: ['todos'] })
65 },
66 }))
67​
68 onAddTodo() {
69 this.addTodoMutation.mutate({
70 id: Date.now().toString(),
71 title: 'Do Laundry',
72 })
73 }
75​
76@Injectable({ providedIn: 'root' })
77export class TodoService {
78 private readonly http = inject(HttpClient)
79​
80 getTodos(): Promise<Todo[]> {
81 return lastValueFrom(
82 this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos'),
83 )
84 }
85​
86 addTodo(todo: Todo): Promise<Todo> {
87 return lastValueFrom(
88 this.http.post<Todo>('https://jsonplaceholder.typicode.com/todos', todo),
89 )
90 }
92​
93interface Todo {
94 id: string
95 title: string
97```
98​
99[//]: # 'Example'