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

inject-mutation.ts

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