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

inject-is-mutating.ts

43 lines1.6 KB

1import { assertInInjectionContext, inject } from '@angular/core'
2import { QueryClient } from '@tanstack/query-core'
3import { injectExternalStore } from './utils/inject-external-store'
4import type { Signal } from '@angular/core'
5import type { MutationFilters } from '@tanstack/query-core'
6​
7/**
8 * Injects a signal that tracks the number of mutations that your application currently has `pending`
9 * (useful for app-wide loading indicators).
10 * @param filters - A function returning the {@link MutationFilters} to narrow down the matched mutations.
11 * Similar to `computed` from Angular, this function runs in the reactive context, so signals read inside it
12 * re-narrow the matched mutations.
13 * @returns A `Signal` with the number of mutations that your application currently has `pending`.
14 * @example
15 * ```angular-ts
16 * @Component({
17 * selector: 'posts-mutating-indicator',
18 * template: `
19 * @if (isMutatingPosts()) {
20 * <span>Saving posts...</span>
21 * }
22 * `,
23 * })
24 * export class PostsMutatingIndicator {
25 * // How many mutations matching the posts prefix are in progress?
26 * readonly isMutatingPosts = injectIsMutating(() => ({ mutationKey: ['posts'] }))
27 * }
28 * ```
29 */
30export function injectIsMutating(
31 filters: () => Omit<MutationFilters, 'status'> = () => ({}),
32): Signal<number> {
33 if (typeof ngDevMode === 'undefined' || ngDevMode) {
34 assertInInjectionContext(injectIsMutating)
35 }
36 const queryClient = inject(QueryClient)
37 const cache = queryClient.getMutationCache()
38​
39 return injectExternalStore(() => ({
40 getSnapshot: () => queryClient.isMutating(filters()),
41 subscribe: (onStoreChange) => cache.subscribe(onStoreChange),
42 }))