TTMT.ManageWebGUI/src/hooks/useMutationData.ts

43 lines
1.0 KiB
TypeScript
Raw Normal View History

2025-08-11 23:21:36 +07:00
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
}
2025-08-11 23:21:36 +07:00
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,
})
}