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

inject-mutation.ts

160 lines4.3 KB

1import {
2 DestroyRef,
3 NgZone,
4 computed,
5 effect,
6 inject,
7 signal,
8 untracked,
9} from '@angular/core'
10import {
11 MutationObserver,
12 QueryClient,
13 notifyManager,
14} from '@tanstack/query-core'
15import { assertInjector } from './util/assert-injector/assert-injector'
16import { signalProxy } from './signal-proxy'
17import { noop, shouldThrowError } from './util'
18import type { Injector } from '@angular/core'
19import type { DefaultError, MutationObserverResult } from '@tanstack/query-core'
20import type { CreateMutateFunction, CreateMutationResult } from './types'
21import type { CreateMutationOptions } from './mutation-options'
22​
23/**
24 * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
25 *
26 * Unlike queries, mutations are not run automatically.
27 * @param optionsFn - A function that returns mutation options.
28 * @param injector - The Angular injector to use.
29 * @returns The mutation.
30 * @public
31 */
32export function injectMutation<
33 TData = unknown,
34 TError = DefaultError,
35 TVariables = void,
36 TContext = unknown,
37>(
38 optionsFn: () => CreateMutationOptions<TData, TError, TVariables, TContext>,
39 injector?: Injector,
40): CreateMutationResult<TData, TError, TVariables, TContext> {
41 return assertInjector(injectMutation, injector, () => {
42 const destroyRef = inject(DestroyRef)
43 const ngZone = inject(NgZone)
44 const queryClient = inject(QueryClient)
45​
46 /**
47 * computed() is used so signals can be inserted into the options
48 * making it reactive. Wrapping options in a function ensures embedded expressions
49 * are preserved and can keep being applied after signal changes
50 */
51 const optionsSignal = computed(optionsFn)
52​
53 const observerSignal = (() => {
54 let instance: MutationObserver<
55 TData,
56 TError,
57 TVariables,
58 TContext
59 > | null = null
60​
61 return computed(() => {
62 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
63 })
64 })()
65​
66 const mutateFnSignal = computed<
67 CreateMutateFunction<TData, TError, TVariables, TContext>
68 >(() => {
69 const observer = observerSignal()
70 return (variables, mutateOptions) => {
71 observer.mutate(variables, mutateOptions).catch(noop)
72 }
73 })
74​
75 /**
76 * Computed signal that gets result from mutation cache based on passed options
77 */
78 const resultFromInitialOptionsSignal = computed(() => {
79 const observer = observerSignal()
80 return observer.getCurrentResult()
81 })
82​
83 /**
84 * Signal that contains result set by subscriber
85 */
86 const resultFromSubscriberSignal = signal<MutationObserverResult<
87 TData,
88 TError,
89 TVariables,
90 TContext
91 > | null>(null)
92​
93 effect(
94 () => {
95 const observer = observerSignal()
96 const options = optionsSignal()
97​
98 untracked(() => {
99 observer.setOptions(options)
100 })
101 },
102 {
103 injector,
104 },
105 )
106​
107 effect(
108 () => {
109 // observer.trackResult is not used as this optimization is not needed for Angular
110 const observer = observerSignal()
111​
112 untracked(() => {
113 const unsubscribe = ngZone.runOutsideAngular(() =>
114 observer.subscribe(
115 notifyManager.batchCalls((state) => {
116 ngZone.run(() => {
117 if (
118 state.isError &&
119 shouldThrowError(observer.options.throwOnError, [
120 state.error,
121 ])
122 ) {
123 ngZone.onError.emit(state.error)
124 throw state.error
125 }
126​
127 resultFromSubscriberSignal.set(state)
128 })
129 }),
130 ),
131 )
132 destroyRef.onDestroy(unsubscribe)
133 })
134 },
135 {
136 injector,
137 },
138 )
139​
140 const resultSignal = computed(() => {
141 const resultFromSubscriber = resultFromSubscriberSignal()
142 const resultFromInitialOptions = resultFromInitialOptionsSignal()
143​
144 const result = resultFromSubscriber ?? resultFromInitialOptions
145​
146 return {
147 ...result,
148 mutate: mutateFnSignal(),
149 mutateAsync: result.mutate,
150 }
151 })
152​
153 return signalProxy(resultSignal) as CreateMutationResult<
154 TData,
155 TError,
156 TVariables,
157 TContext
158 >
159 })