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

inject-is-fetching.ts

65 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 */
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 // isFetching is the prev value initialized on mount *
43 let isFetching = queryClient.isFetching(filters)
44​
45 const result = signal(isFetching)
46​
47 const unsubscribe = ngZone.runOutsideAngular(() =>
48 cache.subscribe(
49 notifyManager.batchCalls(() => {
50 const newIsFetching = queryClient.isFetching(filters)
51 if (isFetching !== newIsFetching) {
52 // * and update with each change
53 isFetching = newIsFetching
54 ngZone.run(() => {
55 result.set(isFetching)
56 })
57 }
58 }),
59 ),
60 )
61​
62 destroyRef.onDestroy(unsubscribe)
63​
64 return result