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

quick-start.md

104 lines2.5 KB

1---
2id: quick-start
3title: Quick Start
4---
5​
6> VERY IMPORTANT: This library is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Use at your own risk. If you choose to rely on this in production in an experimental stage, please lock your version to a patch-level version to avoid unexpected breakages.
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 provideAngularQuery,
18 QueryClient,
19} from '@tanstack/angular-query-experimental'
20​
21bootstrapApplication(AppComponent, {
22 providers: [provideHttpClient(), provideAngularQuery(new QueryClient())],
23})
24```
25​
26### Component with query and mutation
27​
28```ts
29import { Component, Injectable, inject } from '@angular/core'
30import { HttpClient } from '@angular/common/http'
31import { lastValueFrom } from 'rxjs'
32​
33import {
34 injectMutation,
35 injectQuery,
36 injectQueryClient,
37} from '@tanstack/angular-query-experimental'
38​
39@Component({
40 standalone: true,
41 template: `
42 <div>
43 <button (click)="onAddTodo()">Add Todo</button>
44​
45 <ul>
46 @for (todo of query.data(); track todo.title) {
47 <li>{{ todo.title }}</li>
48 }
49 </ul>
50 </div>
51 `,
52})
53export class TodosComponent {
54 todoService = inject(TodoService)
55 queryClient = injectQueryClient()
56​
57 query = injectQuery(() => ({
58 queryKey: ['todos'],
59 queryFn: () => this.todoService.getTodos(),
60 }))
61​
62 mutation = injectMutation((client) => ({
63 mutationFn: (todo: Todo) => this.todoService.addTodo(todo),
64 onSuccess: () => {
65 // Invalidate and refetch by using the client directly
66 client.invalidateQueries({ queryKey: ['todos'] })
67​
68 // OR use the queryClient that is injected into the component
69 // this.queryClient.invalidateQueries({ queryKey: ['todos'] })
70 },
71 }))
72​
73 onAddTodo() {
74 this.mutation.mutate({
75 id: Date.now().toString(),
76 title: 'Do Laundry',
77 })
78 }
80​
81@Injectable({ providedIn: 'root' })
82export class TodoService {
83 private http = inject(HttpClient)
84​
85 getTodos(): Promise<Todo[]> {
86 return lastValueFrom(
87 this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos'),
88 )
89 }
90​
91 addTodo(todo: Todo): Promise<Todo> {
92 return lastValueFrom(
93 this.http.post<Todo>('https://jsonplaceholder.typicode.com/todos', todo),
94 )
95 }
97​
98interface Todo {
99 id: string
100 title: string
102```
103​
104[//]: # 'Example'