Presupuestador_web/client/src/lib/hooks/useAuth/useLogin.tsx
2024-07-01 19:12:15 +02:00

39 lines
1.2 KiB
TypeScript

import { AuthActionResponse, useAuth } from "@/lib/hooks";
import { ILogin_DTO } from "@shared/contexts";
import { UseMutationOptions, useMutation } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { useQueryKey } from "../useQueryKey";
export const useLogin = (params?: UseMutationOptions<AuthActionResponse, Error, ILogin_DTO>) => {
const { onSuccess, onError, ...restParams } = params || {};
const keys = useQueryKey();
const { login } = useAuth();
const navigate = useNavigate();
return useMutation({
mutationKey: keys().auth().action("login").get(),
mutationFn: login,
onSuccess: (data, variables, context) => {
const { success, redirectTo } = data;
if (success && redirectTo) {
navigate(redirectTo || "/", { replace: true });
}
if (onSuccess) {
onSuccess(data, variables, context);
}
},
onError: (error, variables, context) => {
const { message } = error;
console.error(message);
toast.error(message);
if (onError) {
onError(error, variables, context);
}
},
...restParams,
});
};