import React, { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; // ui import { CheckCircleIcon } from "@heroicons/react/20/solid"; import { Input, SecondaryButton } from "components/ui"; // services import authenticationService from "services/authentication.service"; import useToast from "hooks/use-toast"; import useTimer from "hooks/use-timer"; // icons // types type EmailCodeFormValues = { email: string; key?: string; token?: string; }; export const EmailCodeForm = ({ onSuccess }: any) => { const [codeSent, setCodeSent] = useState(false); const [codeResent, setCodeResent] = useState(false); const [isCodeResending, setIsCodeResending] = useState(false); const [errorResendingCode, setErrorResendingCode] = useState(false); const { setToastAlert } = useToast(); const { timer: resendCodeTimer, setTimer: setResendCodeTimer } = useTimer(); const { register, handleSubmit, setError, setValue, getValues, formState: { errors, isSubmitting, isValid, isDirty }, } = useForm({ defaultValues: { email: "", key: "", token: "", }, mode: "onChange", reValidateMode: "onChange", }); const isResendDisabled = resendCodeTimer > 0 || isCodeResending || isSubmitting || errorResendingCode; const onSubmit = async ({ email }: EmailCodeFormValues) => { setErrorResendingCode(false); await authenticationService .emailCode({ email }) .then((res) => { setValue("key", res.key); setCodeSent(true); }) .catch((err) => { setErrorResendingCode(true); setToastAlert({ title: "Oops!", type: "error", message: err?.error, }); }); }; const handleSignin = async (formData: EmailCodeFormValues) => { await authenticationService .magicSignIn(formData) .then((response) => { onSuccess(response); }) .catch((error) => { setToastAlert({ title: "Oops!", type: "error", message: error?.response?.data?.error ?? "Enter the correct code to sign in", }); setError("token" as keyof EmailCodeFormValues, { type: "manual", message: error.error, }); }); }; const emailOld = getValues("email"); useEffect(() => { setErrorResendingCode(false); }, [emailOld]); return ( <>
{(codeSent || codeResent) && (

{codeResent ? "Please check your mail for new code." : "Please check your mail for code."}

)}
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test( value ) || "Email ID is not valid", }} error={errors.email} placeholder="Enter your Email ID" />
{codeSent && (
)}
{codeSent ? ( {isSubmitting ? "Signing in..." : "Sign in"} ) : ( { handleSubmit(onSubmit)().then(() => { setResendCodeTimer(30); }); }} loading={isSubmitting || (!isValid && isDirty)} > {isSubmitting ? "Sending code..." : "Send code"} )}
); };