All files / src/hooks useLogin.ts

0% Statements 0/22
0% Branches 0/4
0% Functions 0/5
0% Lines 0/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                                                                                                                                 
import * as yup from "yup";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useQuery, useMutation } from "@tanstack/react-query";
 
import useUserStore from "@/store/useUserStore";
import { IApiFunction } from "@/interfaces";
 
interface ILoginPayload {
  username: string;
  password: string;
  requestToken?: string;
}
 
const loginSchema = yup.object().shape({
  username: yup.string().required("Username field is required"),
  password: yup.string().required("Password field is required"),
});
 
const useLogin = (apiFunctions: IApiFunction) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
 
  const { accentColor } = useUserStore();
 
  const { data: requestToken } = useQuery({
    queryKey: [apiFunctions.getRequestToken.key],
    queryFn: () => apiFunctions.getRequestToken.func(),
  });
 
  const {
    mutateAsync: loginMutation,
    isPending: loginLoading,
    error,
  } = useMutation({
    mutationFn: (payload: ILoginPayload) => apiFunctions.login.func(payload),
  });
 
  const { mutateAsync: createSessionMutation } = useMutation({
    mutationFn: (payload: { requestToken: string }) => apiFunctions.createSession.func(payload),
  });
 
  const handleLogin = async (payload: ILoginPayload) => {
    try {
      const loginResponse = await loginMutation({
        username: payload.username,
        password: payload.password,
        requestToken: requestToken?.request_token ?? "",
      });
 
      if (!loginResponse.success) return;
 
      const createSessionResponse = await createSessionMutation({
        requestToken: loginResponse.request_token,
      });
 
      useUserStore.setState({
        sessionId: createSessionResponse.session_id,
      });
 
      useUserStore.setState({ isAuthenticated: true });
      navigate("/");
    } catch (e) {
      console.log(e);
    }
  };
 
  return {
    loginLoading,
    error,
    createSessionMutation,
    loginSchema,
    t,
    navigate,
    handleLogin,
    accentColor,
  };
};
 
export default useLogin;