43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
|
import axios, { type Method } from "axios"
|
|
|
|
type MutationDataOptions<TInput, TOutput> = {
|
|
url: string
|
|
method?: Method // POST, PUT, PATCH, DELETE
|
|
onSuccess?: (data: TOutput) => void
|
|
onError?: (error: any) => void
|
|
config?: {
|
|
onUploadProgress?: (e: ProgressEvent) => void
|
|
}
|
|
invalidate?: string[][] // List of queryKeys to invalidate
|
|
}
|
|
|
|
export function useMutationData<TInput = any, TOutput = any>({
|
|
url,
|
|
method = "POST",
|
|
onSuccess,
|
|
onError,
|
|
invalidate = [],
|
|
}: MutationDataOptions<TInput, TOutput>) {
|
|
const queryClient = useQueryClient()
|
|
|
|
return useMutation<TOutput, any, TInput>({
|
|
mutationFn: async (data: TInput) => {
|
|
const response = await axios.request({
|
|
url,
|
|
method,
|
|
data,
|
|
})
|
|
return response.data
|
|
},
|
|
onSuccess: (data) => {
|
|
invalidate.forEach((key) =>
|
|
queryClient.invalidateQueries({ queryKey: key })
|
|
)
|
|
onSuccess?.(data)
|
|
},
|
|
onError,
|
|
})
|
|
}
|
|
|