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

inject-is-fetching.ts

60 lines1.7 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 A read-only signal with the number of loading or fetching queries.
30 */
31export function injectIsFetching(
32 filters?: QueryFilters,
33 options?: InjectIsFetchingOptions,
34): Signal<number> {
35 !options?.injector && assertInInjectionContext(injectIsFetching)
36 const injector = options?.injector ?? inject(Injector)
37 const destroyRef = injector.get(DestroyRef)
38 const ngZone = injector.get(NgZone)
39 const queryClient = injector.get(QueryClient)
40​
41 const cache = queryClient.getQueryCache()
42 const result = signal(queryClient.isFetching(filters))
43​
44 const unsubscribe = ngZone.runOutsideAngular(() =>
45 cache.subscribe(
46 notifyManager.batchCalls(() => {
47 const newIsFetching = queryClient.isFetching(filters)
48 if (result() !== newIsFetching) {
49 ngZone.run(() => {
50 result.set(newIsFetching)
51 })
52 }
53 }),
54 ),
55 )
56​
57 destroyRef.onDestroy(unsubscribe)
58​
59 return result.asReadonly()