Open History to see the last commit
1import { shallowRef } from 'vue'
2β
3export function useMutation<TVariables, TData, TError = Error>(opts: {
4 fn: (variables: TVariables) => Promise<TData>
5 onSuccess?: (ctx: { data: TData }) => void | Promise<void>
6}) {
7 const submittedAt = shallowRef<number | undefined>(undefined)
8 const variables = shallowRef<TVariables | undefined>(undefined)
9 const error = shallowRef<TError | undefined>(undefined)
10 const data = shallowRef<TData | undefined>(undefined)
11 const status = shallowRef<'idle' | 'pending' | 'success' | 'error'>('idle')
12β
13 const mutate = async (
14 variablesInput: TVariables,
15 ): Promise<TData | undefined> => {
16 status.value = 'pending'
17 submittedAt.value = Date.now()
18 variables.value = variablesInput
19 try {
20 const result = await opts.fn(variablesInput)
21 await opts.onSuccess?.({ data: result })
22 status.value = 'success'
23 error.value = undefined
24 data.value = result
25 return result
26 } catch (err) {
27 status.value = 'error'
28 error.value = err as TError
29 }
30 }
31β
32 return {
33 status,
34 variables,
35 submittedAt,
36 mutate,
37 error,
38 data,
39 }
40}