File size: 1,867 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import { MutationObserver, noop, shouldThrowError } from '@tanstack/query-core'
import { createComputed, createMemo, on, onCleanup } from 'solid-js'
import { createStore } from 'solid-js/store'
import { useQueryClient } from './QueryClientProvider'
import type { DefaultError } from '@tanstack/query-core'
import type { QueryClient } from './QueryClient'
import type {
UseMutateFunction,
UseMutationOptions,
UseMutationResult,
} from './types'
import type { Accessor } from 'solid-js'
// HOOK
export function useMutation<
TData = unknown,
TError = DefaultError,
TVariables = void,
TContext = unknown,
>(
options: UseMutationOptions<TData, TError, TVariables, TContext>,
queryClient?: Accessor<QueryClient>,
): UseMutationResult<TData, TError, TVariables, TContext> {
const client = createMemo(() => useQueryClient(queryClient?.()))
const observer = new MutationObserver<TData, TError, TVariables, TContext>(
client(),
options(),
)
const mutate: UseMutateFunction<TData, TError, TVariables, TContext> = (
variables,
mutateOptions,
) => {
observer.mutate(variables, mutateOptions).catch(noop)
}
const [state, setState] = createStore<
UseMutationResult<TData, TError, TVariables, TContext>
>({
...observer.getCurrentResult(),
mutate,
mutateAsync: observer.getCurrentResult().mutate,
})
createComputed(() => {
observer.setOptions(options())
})
createComputed(
on(
() => state.status,
() => {
if (
state.isError &&
shouldThrowError(observer.options.throwOnError, [state.error])
) {
throw state.error
}
},
),
)
const unsubscribe = observer.subscribe((result) => {
setState({
...result,
mutate,
mutateAsync: result.mutate,
})
})
onCleanup(unsubscribe)
return state
}
|