Open History to see the last commit
1import {
2 Injector,
3 NgZone,
4 assertInInjectionContext,
5 computed,
6 effect,
7 inject,
8 signal,
9 untracked,
10} from '@angular/core'
11import {
12 MutationObserver,
13 QueryClient,
14 noop,
15 notifyManager,
16 shouldThrowError,
17} from '@tanstack/query-core'
18import { signalProxy } from './signal-proxy'
19import { PENDING_TASKS } from './pending-tasks-compat'
20import type { PendingTaskRef } from './pending-tasks-compat'
21import type { DefaultError, MutationObserverResult } from '@tanstack/query-core'
22import type {
23 CreateMutateFunction,
24 CreateMutationOptions,
25 CreateMutationResult,
26} from './types'
27β
28export interface InjectMutationOptions {
29 /**
30 * The `Injector` in which to create the mutation.
31 *
32 * If this is not provided, the current injection context will be used instead (via `inject`).
33 */
34 injector?: Injector
35}
36β
37/**
38 * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
39 *
40 * Unlike queries, mutations are not run automatically.
41 * @param injectMutationFn - A function that returns mutation options.
42 * @param options - Additional configuration
43 * @returns The mutation.
44 */
45export function injectMutation<
46 TData = unknown,
47 TError = DefaultError,
48 TVariables = void,
49 TOnMutateResult = unknown,
50>(
51 injectMutationFn: () => CreateMutationOptions<
52 TData,
53 TError,
54 TVariables,
55 TOnMutateResult
56 >,
57 options?: InjectMutationOptions,
58): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
59 !options?.injector && assertInInjectionContext(injectMutation)
60 const injector = options?.injector ?? inject(Injector)
61 const ngZone = injector.get(NgZone)
62 const pendingTasks = injector.get(PENDING_TASKS)
63 const queryClient = injector.get(QueryClient)
64β
65 /**
66 * computed() is used so signals can be inserted into the options
67 * making it reactive. Wrapping options in a function ensures embedded expressions
68 * are preserved and can keep being applied after signal changes
69 */
70 const optionsSignal = computed(injectMutationFn)
71β
72 const observerSignal = (() => {
73 let instance: MutationObserver<
74 TData,
75 TError,
76 TVariables,
77 TOnMutateResult
78 > | null = null
79β
80 return computed(() => {
81 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
82 })
83 })()
84β
85 const mutateFnSignal = computed<
86 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
87 >(() => {
88 const observer = observerSignal()
89 return (variables, mutateOptions) => {
90 observer.mutate(variables, mutateOptions).catch(noop)
91 }
92 })
93β
94 /**
95 * Computed signal that gets result from mutation cache based on passed options
96 */
97 const resultFromInitialOptionsSignal = computed(() => {
98 const observer = observerSignal()
99 return observer.getCurrentResult()
100 })
101β
102 /**
103 * Signal that contains result set by subscriber
104 */
105 const resultFromSubscriberSignal = signal<MutationObserverResult<
106 TData,
107 TError,
108 TVariables,
109 TOnMutateResult
110 > | null>(null)
111β
112 effect(
113 () => {
114 const observer = observerSignal()
115 const observerOptions = optionsSignal()
116β
117 untracked(() => {
118 observer.setOptions(observerOptions)
119 })
120 },
121 {
122 injector,
123 },
124 )
125β
126 effect(
127 (onCleanup) => {
128 // observer.trackResult is not used as this optimization is not needed for Angular
129 const observer = observerSignal()
130 let pendingTaskRef: PendingTaskRef | null = null
131β
132 untracked(() => {
133 const unsubscribe = ngZone.runOutsideAngular(() =>
134 observer.subscribe(
135 notifyManager.batchCalls((state) => {
136 ngZone.run(() => {
137 // Track pending task when mutation is pending
138 if (state.isPending && !pendingTaskRef) {
139 pendingTaskRef = pendingTasks.add()
140 }
141β
142 // Clear pending task when mutation is no longer pending
143 if (!state.isPending && pendingTaskRef) {
144 pendingTaskRef()
145 pendingTaskRef = null
146 }
147β
148 if (
149 state.isError &&
150 shouldThrowError(observer.options.throwOnError, [state.error])
151 ) {
152 ngZone.onError.emit(state.error)
153 throw state.error
154 }
155β
156 resultFromSubscriberSignal.set(state)
157 })
158 }),
159 ),
160 )
161 onCleanup(() => {
162 // Clean up any pending task on destroy
163 if (pendingTaskRef) {
164 pendingTaskRef()
165 pendingTaskRef = null
166 }
167 unsubscribe()
168 })
169 })
170 },
171 {
172 injector,
173 },
174 )
175β
176 const resultSignal = computed(() => {
177 const resultFromSubscriber = resultFromSubscriberSignal()
178 const resultFromInitialOptions = resultFromInitialOptionsSignal()
179β
180 const result = resultFromSubscriber ?? resultFromInitialOptions
181β
182 return {
183 ...result,
184 mutate: mutateFnSignal(),
185 mutateAsync: result.mutate,
186 }
187 })
188β
189 return signalProxy(resultSignal) as CreateMutationResult<
190 TData,
191 TError,
192 TVariables,
193 TOnMutateResult
194 >
195}