All files / src/componentsV2/AccountProfile/AccountDetails ChangeEmailModal.tsx

93.1% Statements 27/29
50% Branches 2/4
87.5% Functions 7/8
92.85% Lines 26/28

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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158                                                      3x       3x 79x 79x 79x 79x 79x   79x               14x       79x           79x   79x 2x             79x 2x       1x   1x     1x 1x     1x 1x 1x 1x           79x         79x                                                                                                           79x                  
import { Box } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveText from "@shared/Text/GiveText";
import { useMutation, useQueryClient } from "react-query";
import { styled } from "@theme/v2/Provider";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useAppSelector } from "@redux/hooks";
import { selectUser } from "@redux/slices/auth/auth";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { customInstance } from "@services/api";
import { showMessage } from "@common/Toast";
import { HFGiveInput } from "@shared/HFInputs/HFGiveInput/HFGiveInput";
import { useGetUser } from "@services/api/onboarding/user";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { VALIDATION_MESSAGES } from "@validation/messages";
 
type Props = {
  setPasswordChecked: React.Dispatch<React.SetStateAction<boolean>>;
};
 
type IFormInputs = {
  email: string;
};
 
const defaultValues = {
  email: "",
};
 
const ChangeEmailModal = ({ setPasswordChecked }: Props) => {
  const { open, onClose } = useNiceModal();
  const queryClient = useQueryClient();
  const { email: currentEmail } = useAppSelector(selectUser);
  const { data: userData } = useGetUser();
  const { isMobileView } = useCustomThemeV2();
 
  const schema = Yup.object({
    email: Yup.string()
      .required(VALIDATION_MESSAGES.EMAIL_REQUIRED)
      .email(VALIDATION_MESSAGES.INVALID_EMAIL)
      .test(
        "same-email",
        "Email already associated with your account",
        (value) =>
          value?.toLocaleLowerCase() !== currentEmail?.toLocaleLowerCase(),
      ),
  });
 
  const methods = useForm<IFormInputs>({
    mode: "onSubmit",
    resolver: yupResolver(schema),
    defaultValues: defaultValues,
  });
 
  const { setError } = methods;
 
  const updateUserData = useMutation((data: any) => {
    return customInstance({
      url: `/users/${userData?.accID}`,
      method: "PATCH",
      data,
    });
  });
 
  const onSubmit: SubmitHandler<IFormInputs> = (data) => {
    updateUserData.mutate(
      { email: data.email },
      {
        onError: (err: any) => {
          const errMessage = err.response?.data?.input[0]?.message;
          const inputError =
            errMessage === 'The provided "email" value is already taken.'
              ? "Email already used"
              : errMessage;
          setError("email", { message: inputError });
          showMessage("Error", errMessage);
        },
        onSuccess: () => {
          showMessage("Info", "Check your email to validate your new email");
          queryClient.invalidateQueries("user");
          onClose();
          setPasswordChecked(false);
        },
      },
    );
  };
 
  const handleCancel = () => {
    onClose();
    setPasswordChecked(false);
  };
 
  return (
    <GiveBaseModal
      open={open}
      title="Change Email"
      width="480px"
      onClose={onClose}
      {...(isMobileView && {
        height: "50%",
      })}
      buttons={
        <>
          <GiveButton
            variant="ghost"
            size="large"
            label="Cancel"
            onClick={handleCancel}
            disabled={updateUserData.isLoading}
          />
 
          <GiveButton
            size="large"
            variant="filled"
            label="Change"
            type="submit"
            form="change-email-form"
            data-testid="submit-button"
            disabled={updateUserData.isLoading}
            sx={{ border: "none" }}
          />
        </>
      }
    >
      <FormProvider {...methods}>
        <Container
          component="form"
          id="change-email-form"
          onSubmit={methods.handleSubmit(onSubmit)}
        >
          <GiveText variant="bodyS" color="secondary">
            You will receive a verification link on your new email address.
            Please click on that link to confirm the email change.
          </GiveText>
          <HFGiveInput
            name="email"
            label="New Email Address"
            placeholder="New Email Address"
            fullWidth
          />
        </Container>
      </FormProvider>
    </GiveBaseModal>
  );
};
 
const Container = styled(Box)(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  width: "100%",
  gap: "24px",
}));
 
export default ChangeEmailModal;