Open History to see the last commit
1import { MutationObserver, noop, shouldThrowError } from '@tanstack/query-core'
2import { createComputed, createMemo, on, onCleanup } from 'solid-js'
3import { createStore } from 'solid-js/store'
4import { useQueryClientResolver } from './QueryClientProvider'
5import type { DefaultError } from '@tanstack/query-core'
6import type { QueryClient } from './QueryClient'
7import type {
8 UseMutateFunction,
9 UseMutationOptions,
10 UseMutationResult,
11} from './types'
12import type { Accessor } from 'solid-js'
13β
14/**
15 * @param options - An accessor returning the {@link UseMutationOptions} to use.
16 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
17 * will be used.
18 * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
19 * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
20 * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
21 * fire only for the latest call you've made, and only while the component is still mounted β unmounting before
22 * the mutation settles removes the subscription and prevents them from firing.
23 *
24 * @example
25 * ```tsx
26 * import { useMutation, useQueryClient } from '@tanstack/solid-query'
27 *
28 * function TodoItem(props: { id: number }) {
29 * const queryClient = useQueryClient()
30 *
31 * const deleteTodoMutation = useMutation(() => ({
32 * mutationFn: deleteTodo,
33 * onSuccess: () => {
34 * queryClient.invalidateQueries({ queryKey: ['todos'] })
35 * },
36 * }))
37 *
38 * return (
39 * <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
40 * Delete
41 * </button>
42 * )
43 * }
44 * ```
45 */
46export function useMutation<
47 TData = unknown,
48 TError = DefaultError,
49 TVariables = void,
50 TOnMutateResult = unknown,
51>(
52 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
53 queryClient?: Accessor<QueryClient>,
54): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
55 const resolveClient = useQueryClientResolver(queryClient)
56 const client = createMemo(() => resolveClient())
57β
58 const observer = new MutationObserver<
59 TData,
60 TError,
61 TVariables,
62 TOnMutateResult
63 >(client(), options())
64β
65 const mutate: UseMutateFunction<
66 TData,
67 TError,
68 TVariables,
69 TOnMutateResult
70 > = (...args) => {
71 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
72 }
73β
74 const [state, setState] = createStore<
75 UseMutationResult<TData, TError, TVariables, TOnMutateResult>
76 >({
77 ...observer.getCurrentResult(),
78 mutate,
79 mutateAsync: observer.getCurrentResult().mutate,
80 })
81β
82 createComputed(() => {
83 observer.setOptions(options())
84 })
85β
86 createComputed(
87 on(
88 () => state.status,
89 () => {
90 if (
91 state.isError &&
92 shouldThrowError(observer.options.throwOnError, [state.error])
93 ) {
94 throw state.error
95 }
96 },
97 ),
98 )
99β
100 const unsubscribe = observer.subscribe((result) => {
101 setState({
102 ...result,
103 mutate,
104 mutateAsync: result.mutate,
105 })
106 })
107β
108 onCleanup(unsubscribe)
109β
110 return state
111}