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

queries.md

104 lines2.3 KB

1---
2id: queries
3title: Queries
4ref: docs/framework/react/guides/queries.md
5replace:
6 {
7 'React': 'Angular',
8 'react-query': 'angular-query',
9 'promise': 'promise or observable',
10 'custom hooks': 'services',
11 'the `useQuery` hook': '`injectQuery`',
12 '`useQuery`': '`injectQuery`',
13 "TypeScript will also narrow the type of data correctly if you've checked for pending and error before accessing it.": 'TypeScript will only narrow the type when checking boolean signals such as `isPending` and `isError`.',
14 }
15---
16​
17[//]: # 'Example'
18​
19```ts
20import { injectQuery } from '@tanstack/angular-query-experimental'
21​
22export class TodosComponent {
23 readonly todosQuery = injectQuery(() => ({
24 queryKey: ['todos'],
25 queryFn: fetchTodoList,
26 }))
28```
29​
30[//]: # 'Example'
31[//]: # 'Example2'
32​
33```ts
34todosQuery = injectQuery(() => ({
35 queryKey: ['todos'],
36 queryFn: fetchTodoList,
37}))
38```
39​
40[//]: # 'Example2'
41[//]: # 'Example3'
42​
43```angular-ts
44@Component({
45 selector: 'todos',
46 template: `
47 @if (todosQuery.isPending()) {
48 <span>Loading...</span>
49 } @else if (todosQuery.isError()) {
50 <span>Error: {{ todosQuery.error()?.message }}</span>
51 } @else {
52 <!-- We can assume by this point that status === 'success' -->
53 @for (todo of todosQuery.data(); track todo.id) {
54 <li>{{ todo.title }}</li>
55 } @empty {
56 <li>No todos found</li>
57 }
58 }
59 `,
60})
61export class PostsComponent {
62 readonly todosQuery = injectQuery(() => ({
63 queryKey: ['todos'],
64 queryFn: fetchTodoList,
65 }))
67```
68​
69[//]: # 'Example3'
70​
71If booleans aren't your thing, you can always use the `status` state as well:
72​
73[//]: # 'Example4'
74​
75```angular-ts
76@Component({
77 selector: 'todos',
78 template: `
79 @switch (todosQuery.status()) {
80 @case ('pending') {
81 <span>Loading...</span>
82 }
83 @case ('error') {
84 <span>Error: {{ todosQuery.error()?.message }}</span>
85 }
86 <!-- also status === 'success', but "else" logic works, too -->
87 @default {
88 <ul>
89 @for (todo of todosQuery.data(); track todo.id) {
90 <li>{{ todo.title }}</li>
91 } @empty {
92 <li>No todos found</li>
93 }
94 </ul>
95 }
96 }
97 `,
98})
99class TodosComponent {}
100```
101​
102[//]: # 'Example4'
103[//]: # 'Materials'
104[//]: # 'Materials'