MCPcopy Create free account
hub / github.com/TanStack/query / useMutation

Function useMutation

packages/vue-query/src/useMutation.ts:237–312  ·  view source on GitHub ↗
(
  options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
  queryClient?: QueryClient,
)

Source from the content-addressed store, hash-verified

235 * ```
236 */
237export function useMutation<
238 TData = unknown,
239 TError = DefaultError,
240 TVariables = void,
241 TOnMutateResult = unknown,
242>(
243 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
244 queryClient?: QueryClient,
245): UseMutationReturnType<TData, TError, TVariables, TOnMutateResult> {
246 if (process.env.NODE_ENV === 'development') {
247 if (!getCurrentScope()) {
248 console.warn(
249 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
250 )
251 }
252 }
253
254 const client = queryClient || useQueryClient()
255 const defaultedOptions = computed(() => {
256 const resolvedOptions = typeof options === 'function' ? options() : options
257 return client.defaultMutationOptions(cloneDeepUnref(resolvedOptions))
258 })
259 const observer = new MutationObserver(client, defaultedOptions.value)
260 const state = defaultedOptions.value.shallow
261 ? shallowReactive(observer.getCurrentResult())
262 : reactive(observer.getCurrentResult())
263
264 const unsubscribe = observer.subscribe((result) => {
265 updateState(state, result)
266 })
267
268 const mutate = (
269 ...args: Parameters<
270 MutateFunction<TData, TError, TVariables, TOnMutateResult>
271 >
272 ) => {
273 observer.mutate(args[0] as TVariables, args[1]).catch(() => {
274 // This is intentional
275 })
276 }
277
278 watch(defaultedOptions, () => {
279 observer.setOptions(defaultedOptions.value)
280 })
281
282 onScopeDispose(() => {
283 unsubscribe()
284 })
285
286 const readonlyState = defaultedOptions.value.shallow
287 ? shallowReadonly(state)
288 : readonly(state)
289
290 const resultRefs = toRefs(readonlyState) as ToRefs<
291 Readonly<MutationResult<TData, TError, TVariables, TOnMutateResult>>
292 >
293
294 watch(

Calls 10

getCurrentResultMethod · 0.95
setOptionsMethod · 0.95
useQueryClientFunction · 0.90
cloneDeepUnrefFunction · 0.90
updateStateFunction · 0.90
shouldThrowErrorFunction · 0.90
unsubscribeFunction · 0.70
optionsFunction · 0.50
subscribeMethod · 0.45

Tested by

no test coverage detected