Open History to see the last commit
1import {
2 DestroyRef,
3 Injector,
4 NgZone,
5 computed,
6 effect,
7 inject,
8 runInInjectionContext,
9 signal,
10} from '@angular/core'
11import {
12 MutationObserver,
13 QueryClient,
14 notifyManager,
15} from '@tanstack/query-core'
16import { assertInjector } from './util/assert-injector/assert-injector'
17import { signalProxy } from './signal-proxy'
18import { noop, shouldThrowError } from './util'
19β
20import { lazyInit } from './util/lazy-init/lazy-init'
21import type { DefaultError, MutationObserverResult } from '@tanstack/query-core'
22import type {
23 CreateMutateFunction,
24 CreateMutationOptions,
25 CreateMutationResult,
26} from './types'
27β
28/**
29 * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
30 *
31 * Unlike queries, mutations are not run automatically.
32 * @param optionsFn - A function that returns mutation options.
33 * @param injector - The Angular injector to use.
34 * @returns The mutation.
35 * @public
36 */
37export function injectMutation<
38 TData = unknown,
39 TError = DefaultError,
40 TVariables = void,
41 TContext = unknown,
42>(
43 optionsFn: () => CreateMutationOptions<TData, TError, TVariables, TContext>,
44 injector?: Injector,
45): CreateMutationResult<TData, TError, TVariables, TContext> {
46 return assertInjector(injectMutation, injector, () => {
47 const currentInjector = inject(Injector)
48 const destroyRef = inject(DestroyRef)
49 const ngZone = inject(NgZone)
50 const queryClient = inject(QueryClient)
51β
52 return lazyInit(() =>
53 runInInjectionContext(currentInjector, () => {
54 const observer = new MutationObserver<
55 TData,
56 TError,
57 TVariables,
58 TContext
59 >(queryClient, optionsFn())
60 const mutate: CreateMutateFunction<
61 TData,
62 TError,
63 TVariables,
64 TContext
65 > = (variables, mutateOptions) => {
66 observer.mutate(variables, mutateOptions).catch(noop)
67 }
68β
69 effect(() => {
70 observer.setOptions(
71 runInInjectionContext(currentInjector, () => optionsFn()),
72 )
73 })
74β
75 const result = signal(observer.getCurrentResult())
76β
77 const unsubscribe = observer.subscribe(
78 notifyManager.batchCalls(
79 (
80 state: MutationObserverResult<
81 TData,
82 TError,
83 TVariables,
84 TContext
85 >,
86 ) => {
87 ngZone.run(() => {
88 if (
89 state.isError &&
90 shouldThrowError(observer.options.throwOnError, [state.error])
91 ) {
92 throw state.error
93 }
94 result.set(state)
95 })
96 },
97 ),
98 )
99β
100 destroyRef.onDestroy(unsubscribe)
101β
102 const resultSignal = computed(() => ({
103 ...result(),
104 mutate,
105 mutateAsync: result().mutate,
106 }))
107β
108 return signalProxy(resultSignal) as unknown as CreateMutationResult<
109 TData,
110 TError,
111 TVariables,
112 TContext
113 >
114 }),
115 )
116 })
117}