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

inject-mutation.ts

153 lines4.4 KB

1import {
2 assertInInjectionContext,
3 computed,
4 effect,
5 inject,
6 untracked,
7} from '@angular/core'
8import { MutationObserver, QueryClient, noop } from '@tanstack/query-core'
9import { injectQueryZone } from './utils/inject-query-zone'
10import { signalProxy } from './utils/signal-proxy'
11import { mutationResultFields } from './utils/result-fields'
12import { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'
13import { injectExternalStore } from './utils/inject-external-store'
14import type { DefaultError } from '@tanstack/query-core'
15import type {
16 CreateMutateAsyncFunction,
17 CreateMutateFunction,
18 CreateMutationOptions,
19 CreateMutationResult,
20} from './types'
21​
22/**
23 * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
24 * Unlike queries, mutations are not run automatically.
25 *
26 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations
27 * @see {@link mutationOptions} to share these options between `injectMutation` and `injectMutationState`.
28 * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this
29 * function runs in the reactive context, so signals read inside it drive the mutation.
30 * @returns The mutation result, including `mutate` and `mutateAsync`.
31 *
32 * @example
33 * ```angular-ts
34 * @Component({
35 * template: `
36 * @if (mutation.isPending()) {
37 * Saving...
38 * } @else if (mutation.isError()) {
39 * <span>Error: {{ mutation.error()?.message }}</span>
40 * }
41 * <button (click)="mutation.mutate({ title: 'New post' })">Create</button>
42 * `,
43 * })
44 * export class CreatePost {
45 * readonly mutation = injectMutation(() => ({
46 * mutationFn: createPost,
47 * }))
48 * }
49 * ```
50 */
51export function injectMutation<
52 TData = unknown,
53 TError = DefaultError,
54 TVariables = void,
55 TOnMutateResult = unknown,
56>(
57 optionsFn: () => CreateMutationOptions<
58 TData,
59 TError,
60 TVariables,
61 TOnMutateResult
62 >,
63): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
64 if (typeof ngDevMode === 'undefined' || ngDevMode) {
65 assertInInjectionContext(injectMutation)
66 }
67 const outsideZone = injectQueryZone()
68 const queryClient = inject(QueryClient)
69 const lifecycle = injectPendingTasksLifecycle()
70​
71 const optionsSignal = computed(optionsFn)
72​
73 const observerSignal = computed(
74 () => new MutationObserver(queryClient, untracked(optionsSignal)),
75 )
76​
77 // Configure the observer outside the result computation. Mutation-cache
78 // listeners can synchronously read the public result while setOptions emits.
79 effect(() => {
80 const options = optionsSignal()
81 outsideZone(() => untracked(() => observerSignal().setOptions(options)))
82 })
83​
84 const mutationStateSignal = injectExternalStore(() => {
85 const observer = observerSignal()
86 return {
87 getSnapshot: () => observer.getCurrentResult(),
88 subscribe: (onStoreChange) => observer.subscribe(onStoreChange),
89 }
90 })
91​
92 const mutate: CreateMutateFunction<
93 TData,
94 TError,
95 TVariables,
96 TOnMutateResult
97 > = (...args) => {
98 mutateAsync(...args).catch(noop)
99 }
100​
101 let pendingInvocations = 0
102​
103 const mutateAsync: CreateMutateAsyncFunction<
104 TData,
105 TError,
106 TVariables,
107 TOnMutateResult
108 > = (...args) => {
109 return outsideZone(() =>
110 untracked(() => {
111 const observer = observerSignal()
112 observer.setOptions(optionsSignal())
113 pendingInvocations++
114 lifecycle.setPending(true)
115 // Track invocations, not the observer's latest result: reset or a later
116 // mutation completing must not release work which is still running.
117 const settled = () => {
118 pendingInvocations--
119 lifecycle.setPending(pendingInvocations > 0)
120 }
121 try {
122 return observer
123 .mutate(args[0] as TVariables, args[1])
124 .finally(settled)
125 } catch (error) {
126 settled()
127 throw error
128 }
129 }),
130 )
131 }
132​
133 const reset = () => {
134 outsideZone(() =>
135 untracked(() => {
136 const observer = observerSignal()
137 observer.setOptions(optionsSignal())
138 observer.reset()
139 }),
140 )
141 }
142​
143 return Object.assign(signalProxy(mutationStateSignal, mutationResultFields), {
144 mutate,
145 mutateAsync,
146 reset,
147 }) as unknown as CreateMutationResult<
148 TData,
149 TError,
150 TVariables,
151 TOnMutateResult
152 >