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

quick-start.md

117 lines2.7 KB

1---
2id: quick-start
3title: Quick Start
4---
5​
6> IMPORTANT: This library is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Upgrade carefully. If you use this in production while in experimental stage, please lock your version to a patch-level version to avoid unexpected breaking changes.
7​
8[//]: # 'Example'
9​
10If you're looking for a fully functioning example, please have a look at our [basic codesandbox example](../examples/basic)
11​
12### Provide the client to your App
13​
14```ts
15import { provideHttpClient } from '@angular/common/http'
16import {
17 provideTanStackQuery,
18 QueryClient,
19} from '@tanstack/angular-query-experimental'
20​
21bootstrapApplication(AppComponent, {
22 providers: [provideHttpClient(), provideTanStackQuery(new QueryClient())],
23})
24```
25​
26or in a NgModule-based app
27​
28```ts
29import { provideHttpClient } from '@angular/common/http'
30import {
31 provideTanStackQuery,
32 QueryClient,
33} from '@tanstack/angular-query-experimental'
34​
35@NgModule({
36 declarations: [AppComponent],
37 imports: [BrowserModule],
38 providers: [provideTanStackQuery(new QueryClient())],
39 bootstrap: [AppComponent],
40})
41export class AppModule {}
42```
43​
44### Component with query and mutation
45​
46```angular-ts
47import { Component, Injectable, inject } from '@angular/core'
48import { HttpClient } from '@angular/common/http'
49import { lastValueFrom } from 'rxjs'
50​
51import {
52 injectMutation,
53 injectQuery,
54 QueryClient
55} from '@tanstack/angular-query-experimental'
56​
57@Component({
58 template: `
59 <div>
60 <button (click)="onAddTodo()">Add Todo</button>
61​
62 <ul>
63 @for (todo of query.data(); track todo.title) {
64 <li>{{ todo.title }}</li>
65 }
66 </ul>
67 </div>
68 `,
69})
70export class TodosComponent {
71 todoService = inject(TodoService)
72 queryClient = inject(QueryClient)
73​
74 query = injectQuery(() => ({
75 queryKey: ['todos'],
76 queryFn: () => this.todoService.getTodos(),
77 }))
78​
79 mutation = injectMutation(() => ({
80 mutationFn: (todo: Todo) => this.todoService.addTodo(todo),
81 onSuccess: () => {
82 this.queryClient.invalidateQueries({ queryKey: ['todos'] })
83 },
84 }))
85​
86 onAddTodo() {
87 this.mutation.mutate({
88 id: Date.now().toString(),
89 title: 'Do Laundry',
90 })
91 }
93​
94@Injectable({ providedIn: 'root' })
95export class TodoService {
96 private http = inject(HttpClient)
97​
98 getTodos(): Promise<Todo[]> {
99 return lastValueFrom(
100 this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos'),
101 )
102 }
103​
104 addTodo(todo: Todo): Promise<Todo> {
105 return lastValueFrom(
106 this.http.post<Todo>('https://jsonplaceholder.typicode.com/todos', todo),
107 )
108 }
110​
111interface Todo {
112 id: string
113 title: string
115```
116​
117[//]: # 'Example'