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

example.component.ts

58 lines1.7 KB

1import {
2 ChangeDetectionStrategy,
3 Component,
4 computed,
5 inject,
6} from '@angular/core'
7import { injectInfiniteQuery } from '@tanstack/angular-query-experimental'
8import { lastValueFrom } from 'rxjs'
9import { ProjectStyleDirective } from '../directives/project-style.directive'
10import { ProjectsService } from '../services/projects.service'
11​
12@Component({
13 changeDetection: ChangeDetectionStrategy.OnPush,
14 selector: 'example',
15 standalone: true,
16 templateUrl: './example.component.html',
17 imports: [ProjectStyleDirective],
18})
19export class ExampleComponent {
20 projectsService = inject(ProjectsService)
21​
22 query = injectInfiniteQuery(() => ({
23 queryKey: ['projects'],
24 queryFn: ({ pageParam }) => {
25 return lastValueFrom(this.projectsService.getProjects(pageParam))
26 },
27 initialPageParam: 0,
28 getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined,
29 getNextPageParam: (lastPage) => lastPage.nextId ?? undefined,
30 maxPages: 3,
31 }))
32​
33 nextButtonDisabled = computed(
34 () => !this.#hasNextPage() || this.#isFetchingNextPage(),
35 )
36 nextButtonText = computed(() =>
37 this.#isFetchingNextPage()
38 ? 'Loading more...'
39 : this.#hasNextPage()
40 ? 'Load newer'
41 : 'Nothing more to load',
42 )
43 previousButtonDisabled = computed(
44 () => !this.#hasPreviousPage() || this.#isFetchingNextPage(),
45 )
46 previousButtonText = computed(() =>
47 this.#isFetchingPreviousPage()
48 ? 'Loading more...'
49 : this.#hasPreviousPage()
50 ? 'Load Older'
51 : 'Nothing more to load',
52 )
53​
54 #hasPreviousPage = this.query.hasPreviousPage
55 #hasNextPage = this.query.hasNextPage
56 #isFetchingPreviousPage = this.query.isFetchingPreviousPage
57 #isFetchingNextPage = this.query.isFetchingNextPage