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

inject-is-mutating.ts

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