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

example.component.ts

50 lines1.2 KB

1import { Component, effect, inject, signal, untracked } from '@angular/core'
2import {
3 QueryClient,
4 injectQuery,
5 keepPreviousData,
6 noop,
7} from '@tanstack/angular-query'
8import { ProjectsQueries } from '../services/projects/queries'
9​
10@Component({
11 selector: 'example',
12 templateUrl: './example.component.html',
13})
14export class ExampleComponent {
15 readonly queryClient = inject(QueryClient)
16 readonly #projectsQueries = inject(ProjectsQueries)
17 readonly page = signal(0)
18​
19 readonly query = injectQuery(() => ({
20 ...this.#projectsQueries.list(this.page()),
21 placeholderData: keepPreviousData,
22 staleTime: 5000,
23 }))
24​
25 readonly prefetchEffect = effect(() => {
26 const data = this.query.data()
27 const isPlaceholderData = this.query.isPlaceholderData()
28 const newPage = this.page() + 1
29​
30 untracked(() => {
31 if (!isPlaceholderData && data?.hasMore) {
32 void this.queryClient
33 .query(this.#projectsQueries.list(newPage))
34 .catch(noop)
35 }
36 })
37 })
38​
39 previousPage() {
40 this.page.update((currentPage) => {
41 return Math.max(currentPage - 1, 0)
42 })
43 }
44​
45 nextPage() {
46 this.page.update((currentPage) => {
47 return this.query.data()?.hasMore ? currentPage + 1 : currentPage
48 })
49 }