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