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

inject-mutation-state.ts

175 lines5.4 KB

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