Open History to see the last commit
1import {
2 DestroyRef,
3 Injector,
4 NgZone,
5 assertInInjectionContext,
6 computed,
7 inject,
8 signal,
9} from '@angular/core'
10import {
11 QueryClient,
12 notifyManager,
13 replaceEqualDeep,
14} from '@tanstack/query-core'
15import type { Signal } from '@angular/core'
16import type {
17 Mutation,
18 MutationCache,
19 MutationFilters,
20 MutationState,
21} from '@tanstack/query-core'
22β
23type MutationStateOptions<TResult = MutationState> = {
24 filters?: MutationFilters
25 select?: (mutation: Mutation) => TResult
26}
27β
28/**
29 * Collects the mutations in the cache that match `options.filters`, mapped with
30 * `options.select` (or to their state, by default).
31 *
32 * @param mutationCache - The mutation cache to read.
33 * @param options - The `filters` to match and the `select` function to map each
34 * mutation with.
35 * @returns The selected value of every matching mutation.
36 */
37function getResult<TResult = MutationState>(
38 mutationCache: MutationCache,
39 options: MutationStateOptions<TResult>,
40): Array<TResult> {
41 return mutationCache
42 .findAll(options.filters)
43 .map(
44 (mutation): TResult =>
45 (options.select ? options.select(mutation) : mutation.state) as TResult,
46 )
47}
48β
49/**
50 * Options for `injectMutationState`, passed after the function that returns the
51 * mutation state options.
52 */
53export interface InjectMutationStateOptions {
54 /**
55 * The `Injector` in which to create the mutation state signal.
56 *
57 * If this is not provided, the current injection context will be used instead
58 * (via `inject`).
59 */
60 injector?: Injector
61}
62β
63/**
64 * Injects a signal that gives you access to all mutations in the
65 * `MutationCache`. You can pass `filters` ({@link MutationFilters}) to narrow
66 * down your mutations, and `select` to transform the mutation state.
67 *
68 * @example
69 * Get all variables of all running mutations:
70 * ```angular-ts
71 * @Component({
72 * selector: 'pending-posts',
73 * template: `{{ pendingVariables().length }} posts saving...`,
74 * })
75 * export class PendingPosts {
76 * readonly pendingVariables = injectMutationState(() => ({
77 * filters: { status: 'pending' },
78 * select: (mutation) => mutation.state.variables,
79 * }))
80 * }
81 * ```
82 *
83 * @example
84 * Get all data for specific mutations via the `mutationKey`:
85 * ```angular-ts
86 * const mutationKey = ['posts']
87 *
88 * @Component({
89 * selector: 'posts',
90 * template: `
91 * <button (click)="createPost()">
92 * Create post ({{ savedPosts().length }} saved so far)
93 * </button>
94 * `,
95 * })
96 * export class Posts {
97 * // Some mutation that we want to get the state for
98 * readonly createPostMutation = injectMutation(() => ({
99 * mutationKey,
100 * mutationFn: createPosts,
101 * }))
102 *
103 * readonly savedPosts = injectMutationState(() => ({
104 * // this mutation key needs to match the mutation key of the given mutation (see above)
105 * filters: { mutationKey, status: 'success' },
106 * select: (mutation) => mutation.state.data,
107 * }))
108 *
109 * createPost() {
110 * this.createPostMutation.mutate(['New Post'])
111 * }
112 * }
113 * ```
114 *
115 * @param injectMutationStateFn - A function returning the `filters` to narrow
116 * down matched mutations, and an optional `select` to transform the mutation
117 * state. Similar to `computed` from Angular, this function runs in the
118 * reactive context, so signals read inside it re-narrow the matched
119 * mutations.
120 * @param options - Additional configuration
121 * @returns A `Signal` with an Array of whatever `select` returns for each
122 * matching mutation.
123 */
124export function injectMutationState<TResult = MutationState>(
125 injectMutationStateFn: () => MutationStateOptions<TResult> = () => ({}),
126 options?: InjectMutationStateOptions,
127): Signal<Array<TResult>> {
128 !options?.injector && assertInInjectionContext(injectMutationState)
129 const injector = options?.injector ?? inject(Injector)
130 const destroyRef = injector.get(DestroyRef)
131 const ngZone = injector.get(NgZone)
132 const queryClient = injector.get(QueryClient)
133 const mutationCache = queryClient.getMutationCache()
134β
135 /**
136 * Computed signal that gets result from mutation cache based on passed
137 * options First element is the result, second element is the time when the
138 * result was set
139 */
140 const resultFromOptionsSignal = computed(() => {
141 return [
142 getResult(mutationCache, injectMutationStateFn()),
143 performance.now(),
144 ] as const
145 })
146β
147 /**
148 * Signal that contains result set by subscriber First element is the result,
149 * second element is the time when the result was set
150 */
151 const resultFromSubscriberSignal = signal<[Array<TResult>, number] | null>(
152 null,
153 )
154β
155 /** Returns the last result by either subscriber or options */
156 const effectiveResultSignal = computed(() => {
157 const optionsResult = resultFromOptionsSignal()
158 const subscriberResult = resultFromSubscriberSignal()
159 return subscriberResult && subscriberResult[1] > optionsResult[1]
160 ? subscriberResult[0]
161 : optionsResult[0]
162 })
163β
164 const unsubscribe = ngZone.runOutsideAngular(() =>
165 mutationCache.subscribe(
166 notifyManager.batchCalls(() => {
167 const [lastResult] = effectiveResultSignal()
168 const nextResult = replaceEqualDeep(
169 lastResult,
170 getResult(mutationCache, injectMutationStateFn()),
171 )
172 if (lastResult !== nextResult) {
173 ngZone.run(() => {
174 resultFromSubscriberSignal.set([nextResult, performance.now()])
175 })
176 }
177 }),
178 ),
179 )
180β
181 destroyRef.onDestroy(unsubscribe)
182β
183 return effectiveResultSignal
184}