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