54 lines
1.2 KiB
TypeScript
54 lines
1.2 KiB
TypeScript
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import axios, { type Method } from "axios";
|
|
|
|
type MutationDataOptions<TInput, TOutput> = {
|
|
url: string;
|
|
method?: Method;
|
|
onSuccess?: (data: TOutput) => void;
|
|
onError?: (error: any) => void;
|
|
invalidate?: string[][];
|
|
};
|
|
|
|
export function useMutationData<TInput = any, TOutput = any>({
|
|
url,
|
|
method = "POST",
|
|
onSuccess,
|
|
onError,
|
|
invalidate = [],
|
|
}: MutationDataOptions<TInput, TOutput>) {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation<
|
|
TOutput,
|
|
any,
|
|
{ data: TInput; url?: string; config?: any; method?: Method }
|
|
>({
|
|
mutationFn: async ({
|
|
data,
|
|
config,
|
|
url: customUrl,
|
|
method: customMethod,
|
|
}) => {
|
|
const isFormData = data instanceof FormData;
|
|
|
|
const response = await axios.request({
|
|
url: customUrl ?? url,
|
|
method: customMethod ?? method,
|
|
data,
|
|
headers: {
|
|
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
|
},
|
|
...config,
|
|
});
|
|
return response.data;
|
|
},
|
|
onSuccess: (data) => {
|
|
invalidate.forEach((key) =>
|
|
queryClient.invalidateQueries({ queryKey: key })
|
|
);
|
|
onSuccess?.(data);
|
|
},
|
|
onError,
|
|
});
|
|
}
|