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