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

quick-start.md

97 lines2.3 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/angular/basic)
11​
12### Provide the client to your App
13​
14```ts
15bootstrapApplication(AppComponent, {
16 providers: [provideAngularQuery(new QueryClient())],
17})
18```
19​
20### Component with query and mutation
21​
22```ts
23import { Component, Injectable, inject } from '@angular/core'
24import { HttpClient } from '@angular/common/http'
25import { lastValueFrom } from 'rxjs'
26​
27import {
28 injectMutation,
29 injectQuery,
30 injectQueryClient,
31} from '@tanstack/angular-query-experimental'
32​
33@Component({
34 standalone: true,
35 template: `
36 <div>
37 <button (click)="onAddTodo()">Add Todo</button>
38​
39 <ul>
40 @for (todo of query.data(); track todo.title) {
41 <li>{{ todo.title }}</li>
42 }
43 </ul>
44 </div>
45 `,
46})
47export class TodosComponent {
48 queryClient = injectQueryClient()
49​
50 query = injectQuery(() => ({
51 queryKey: ['todos'],
52 queryFn: () => this.todoService.getTodos(),
53 }))
54​
55 mutation = injectMutation((client) => ({
56 mutationFn: (todo: Todo) => this.todoService.addTodo(todo),
57 onSuccess: () => {
58 // Invalidate and refetch by using the client directly
59 client.invalidateQueries({ queryKey: ['todos'] })
60​
61 // OR use the queryClient that is injected into the component
62 // this.queryClient.invalidateQueries({ queryKey: ['todos'] })
63 },
64 }))
65​
66 onAddTodo() {
67 this.mutation.mutate({
68 id: Date.now().toString(),
69 title: 'Do Laundry',
70 })
71 }
73​
74@Injectable({ providedIn: 'root' })
75export class TodoService {
76 private http = inject(HttpClient)
77​
78 getTodos(): Promise<Todo[]> {
79 return lastValueFrom(
80 this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos'),
81 )
82 }
83​
84 addTodo(todo: Todo): Promise<Todo> {
85 return lastValueFrom(
86 this.http.post<Todo>('https://jsonplaceholder.typicode.com/todos', todo),
87 )
88 }
90​
91interface Todo {
92 id: string
93 title: string
95```
96​
97[//]: # 'Example'