2025-09-24 16:13:57 +07:00
|
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
|
import axios, { type Method } from "axios";
|
2025-08-11 23:21:36 +07:00
|
|
|
|
|
|
|
type MutationDataOptions<TInput, TOutput> = {
|
2025-09-24 16:13:57 +07:00
|
|
|
url: string;
|
|
|
|
method?: Method;
|
|
|
|
onSuccess?: (data: TOutput) => void;
|
|
|
|
onError?: (error: any) => void;
|
|
|
|
invalidate?: string[][];
|
|
|
|
};
|
2025-08-11 23:21:36 +07:00
|
|
|
|
|
|
|
export function useMutationData<TInput = any, TOutput = any>({
|
|
|
|
url,
|
|
|
|
method = "POST",
|
|
|
|
onSuccess,
|
|
|
|
onError,
|
|
|
|
invalidate = [],
|
|
|
|
}: MutationDataOptions<TInput, TOutput>) {
|
2025-09-24 16:13:57 +07:00
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
|
|
|
return useMutation<TOutput, any, { data: TInput; config?: any }>({
|
|
|
|
mutationFn: async ({ data, config }) => {
|
|
|
|
const isFormData = data instanceof FormData;
|
2025-08-11 23:21:36 +07:00
|
|
|
|
|
|
|
const response = await axios.request({
|
|
|
|
url,
|
|
|
|
method,
|
|
|
|
data,
|
2025-09-24 16:13:57 +07:00
|
|
|
headers: {
|
|
|
|
...(isFormData
|
|
|
|
? {}
|
|
|
|
: { "Content-Type": "application/json" }),
|
|
|
|
},
|
|
|
|
...config,
|
|
|
|
});
|
|
|
|
return response.data;
|
2025-08-11 23:21:36 +07:00
|
|
|
},
|
|
|
|
onSuccess: (data) => {
|
|
|
|
invalidate.forEach((key) =>
|
|
|
|
queryClient.invalidateQueries({ queryKey: key })
|
2025-09-24 16:13:57 +07:00
|
|
|
);
|
|
|
|
onSuccess?.(data);
|
2025-08-11 23:21:36 +07:00
|
|
|
},
|
|
|
|
onError,
|
2025-09-24 16:13:57 +07:00
|
|
|
});
|
2025-08-11 23:21:36 +07:00
|
|
|
}
|