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 (
90 ...args: Parameters<
91 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
92 >
93 ) => {
94 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
95 }
96 })
97β
98 /**
99 * Computed signal that gets result from mutation cache based on passed options
100 */
101 const resultFromInitialOptionsSignal = computed(() => {
102 const observer = observerSignal()
103 return observer.getCurrentResult()
104 })
105β
106 /**
107 * Signal that contains result set by subscriber
108 */
109 const resultFromSubscriberSignal = signal<MutationObserverResult<
110 TData,
111 TError,
112 TVariables,
113 TOnMutateResult
114 > | null>(null)
115β
116 effect(
117 () => {
118 const observer = observerSignal()
119 const observerOptions = optionsSignal()
120β
121 untracked(() => {
122 observer.setOptions(observerOptions)
123 })
124 },
125 {
126 injector,
127 },
128 )
129β
130 effect(
131 (onCleanup) => {
132 // observer.trackResult is not used as this optimization is not needed for Angular
133 const observer = observerSignal()
134 let pendingTaskRef: PendingTaskRef | null = null
135β
136 untracked(() => {
137 const unsubscribe = ngZone.runOutsideAngular(() =>
138 observer.subscribe(
139 notifyManager.batchCalls((state) => {
140 ngZone.run(() => {
141 // Track pending task when mutation is pending
142 if (state.isPending && !pendingTaskRef) {
143 pendingTaskRef = pendingTasks.add()
144 }
145β
146 // Clear pending task when mutation is no longer pending
147 if (!state.isPending && pendingTaskRef) {
148 pendingTaskRef()
149 pendingTaskRef = null
150 }
151β
152 if (
153 state.isError &&
154 shouldThrowError(observer.options.throwOnError, [state.error])
155 ) {
156 ngZone.onError.emit(state.error)
157 throw state.error
158 }
159β
160 resultFromSubscriberSignal.set(state)
161 })
162 }),
163 ),
164 )
165 onCleanup(() => {
166 // Clean up any pending task on destroy
167 if (pendingTaskRef) {
168 pendingTaskRef()
169 pendingTaskRef = null
170 }
171 unsubscribe()
172 })
173 })
174 },
175 {
176 injector,
177 },
178 )
179β
180 const resultSignal = computed(() => {
181 const resultFromSubscriber = resultFromSubscriberSignal()
182 const resultFromInitialOptions = resultFromInitialOptionsSignal()
183β
184 const result = resultFromSubscriber ?? resultFromInitialOptions
185β
186 return {
187 ...result,
188 mutate: mutateFnSignal(),
189 mutateAsync: result.mutate,
190 }
191 })
192β
193 return signalProxy(resultSignal) as CreateMutationResult<
194 TData,
195 TError,
196 TVariables,
197 TOnMutateResult
198 >
199}