Open History to see the last commit
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 { MutationFilters } from '@tanstack/query-core'
11import type { Signal } from '@angular/core'
12β
13export interface InjectIsMutatingOptions {
14 /**
15 * The `Injector` in which to create the isMutating signal.
16 *
17 * If this is not provided, the current injection context will be used instead (via `inject`).
18 */
19 injector?: Injector
20}
21β
22/**
23 * Injects a signal that tracks the number of mutations that your application currently has `pending`
24 * (useful for app-wide loading indicators).
25 *
26 * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
27 * @param options - Additional configuration
28 * @returns A `Signal` with the number of mutations that your application currently has `pending`.
29 *
30 * @example
31 * ```angular-ts
32 * @Component({
33 * selector: 'posts-mutating-indicator',
34 * template: `
35 * @if (isMutatingPosts()) {
36 * <span>Saving posts...</span>
37 * }
38 * `,
39 * })
40 * export class PostsMutatingIndicator {
41 * // How many mutations matching the posts prefix are in progress?
42 * isMutatingPosts = injectIsMutating({ mutationKey: ['posts'] })
43 * }
44 * ```
45 */
46export function injectIsMutating(
47 filters?: MutationFilters,
48 options?: InjectIsMutatingOptions,
49): Signal<number> {
50 !options?.injector && assertInInjectionContext(injectIsMutating)
51 const injector = options?.injector ?? inject(Injector)
52 const destroyRef = injector.get(DestroyRef)
53 const ngZone = injector.get(NgZone)
54 const queryClient = injector.get(QueryClient)
55β
56 const cache = queryClient.getMutationCache()
57 // isMutating is the prev value initialized on mount *
58 let isMutating = queryClient.isMutating(filters)
59β
60 const result = signal(isMutating)
61β
62 const unsubscribe = ngZone.runOutsideAngular(() =>
63 cache.subscribe(
64 notifyManager.batchCalls(() => {
65 const newIsMutating = queryClient.isMutating(filters)
66 if (isMutating !== newIsMutating) {
67 // * and update with each change
68 isMutating = newIsMutating
69 ngZone.run(() => {
70 result.set(isMutating)
71 })
72 }
73 }),
74 ),
75 )
76β
77 destroyRef.onDestroy(unsubscribe)
78β
79 return result.asReadonly()
80}