significant refactor
This commit is contained in:
47
src/lib/tanstack-query/hooks/use-server-mutation.ts
Normal file
47
src/lib/tanstack-query/hooks/use-server-mutation.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useMutation, UseMutationOptions } from "@tanstack/react-query";
|
||||
import { ServerResult } from "../types";
|
||||
import toast from '@/lib/sonner'
|
||||
|
||||
export function useServerMutation<TData, TVariables = unknown>(
|
||||
options: Omit<UseMutationOptions<TData, Error, TVariables>, 'mutationFn'> & {
|
||||
mutationFn: (variables: TVariables) => Promise<ServerResult<TData>>;
|
||||
successMessage?: string;
|
||||
showErrorToast?: boolean;
|
||||
showSuccessToast?: boolean;
|
||||
}
|
||||
) {
|
||||
const {
|
||||
mutationFn,
|
||||
successMessage,
|
||||
showErrorToast = true,
|
||||
showSuccessToast = true,
|
||||
onSuccess,
|
||||
onError,
|
||||
...mutationOptions
|
||||
} = options;
|
||||
|
||||
return useMutation({
|
||||
...mutationOptions,
|
||||
mutationFn: async (variables: TVariables) => {
|
||||
const result = await mutationFn(variables);
|
||||
|
||||
if (!result.success) {
|
||||
if (showErrorToast) {
|
||||
toast.error(result.error.userMessage);
|
||||
}
|
||||
throw new Error(result.error.userMessage);
|
||||
}
|
||||
|
||||
return result.data;
|
||||
},
|
||||
onSuccess: (data, variables, context) => {
|
||||
if (showSuccessToast && successMessage) {
|
||||
toast.success(successMessage);
|
||||
}
|
||||
onSuccess?.(data, variables, context);
|
||||
},
|
||||
onError: (error, variables, context) => {
|
||||
onError?.(error, variables, context);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user