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

inject-is-fetching.ts

66 lines1.9 KB

1import {
2 DestroyRef,
3 Injector,
4 NgZone,
5 assertInInjectionContext,
6 inject,
7 signal,
8} from '@angular/core'
9import { QueryClient, notifyManager } from '@tanstack/query-core'
10import type { QueryFilters } from '@tanstack/query-core'
11import type { Signal } from '@angular/core'
12​
13export interface InjectIsFetchingOptions {
14 /**
15 * The `Injector` in which to create the isFetching signal.
16 *
17 * If this is not provided, the current injection context will be used instead (via `inject`).
18 */
19 injector?: Injector
21​
22/**
23 * Injects a signal that tracks the number of queries that your application is loading or
24 * fetching in the background.
25 *
26 * Can be used for app-wide loading indicators
27 * @param filters - The filters to apply to the query.
28 * @param options - Additional configuration
29 * @returns signal with number of loading or fetching queries.
30 * @public
31 */
32export function injectIsFetching(
33 filters?: QueryFilters,
34 options?: InjectIsFetchingOptions,
35): Signal<number> {
36 !options?.injector && assertInInjectionContext(injectIsFetching)
37 const injector = options?.injector ?? inject(Injector)
38 const destroyRef = injector.get(DestroyRef)
39 const ngZone = injector.get(NgZone)
40 const queryClient = injector.get(QueryClient)
41​
42 const cache = queryClient.getQueryCache()
43 // isFetching is the prev value initialized on mount *
44 let isFetching = queryClient.isFetching(filters)
45​
46 const result = signal(isFetching)
47​
48 const unsubscribe = ngZone.runOutsideAngular(() =>
49 cache.subscribe(
50 notifyManager.batchCalls(() => {
51 const newIsFetching = queryClient.isFetching(filters)
52 if (isFetching !== newIsFetching) {
53 // * and update with each change
54 isFetching = newIsFetching
55 ngZone.run(() => {
56 result.set(isFetching)
57 })
58 }
59 }),
60 ),
61 )
62​
63 destroyRef.onDestroy(unsubscribe)
64​
65 return result