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

inject-is-fetching.ts

59 lines2.1 KB

1import { assertInInjectionContext, inject } from '@angular/core'
2import { QueryClient } from '@tanstack/query-core'
3import { injectExternalStore } from './utils/inject-external-store'
4import type { Signal } from '@angular/core'
5import type { QueryFilters } from '@tanstack/query-core'
6​
7/**
8 * Injects a signal that tracks the number of queries that your application is loading or fetching in the
9 * background (useful for app-wide loading indicators).
10 * @param filters - A function returning the {@link QueryFilters} to narrow down the matched queries. Similar
11 * to `computed` from Angular, this function runs in the reactive context, so signals read inside it
12 * re-narrow the matched queries.
13 * @returns A `Signal` with the number of queries that your application is currently loading or fetching in
14 * the background.
15 * @example
16 * ```angular-ts
17 * @Component({
18 * selector: 'posts-fetching-indicator',
19 * template: `
20 * @if (isFetchingPosts()) {
21 * <span>Refreshing posts...</span>
22 * }
23 * `,
24 * })
25 * export class PostsFetchingIndicator {
26 * // How many queries matching the posts prefix are fetching?
27 * readonly isFetchingPosts = injectIsFetching(() => ({ queryKey: ['posts'] }))
28 * }
29 * ```
30 * @example
31 * A global loading indicator for any query fetching in the background, not just the ones on screen:
32 * ```angular-ts
33 * @Component({
34 * selector: 'global-loading-indicator',
35 * template: `
36 * @if (isFetching()) {
37 * <div>Queries are fetching in the background...</div>
38 * }
39 * `,
40 * })
41 * export class GlobalLoadingIndicator {
42 * readonly isFetching = injectIsFetching()
43 * }
44 * ```
45 */
46export function injectIsFetching(
47 filters: () => Omit<QueryFilters, 'fetchStatus'> = () => ({}),
48): Signal<number> {
49 if (typeof ngDevMode === 'undefined' || ngDevMode) {
50 assertInInjectionContext(injectIsFetching)
51 }
52 const queryClient = inject(QueryClient)
53 const cache = queryClient.getQueryCache()
54​
55 return injectExternalStore(() => ({
56 getSnapshot: () => queryClient.isFetching(filters()),
57 subscribe: (onStoreChange) => cache.subscribe(onStoreChange),
58 }))