I am using react, typescript, and Email JS library. I am using the react-hook-form library and yup to validate forms.
I need to catch the form validation errors that are thrown by the react-hook-library and only if there are no errors, an email should be sent with Email JS.
The relevant part of the code is the sendEmail function.
The handleSubmit(onSubmit)(); which is in the sendEmail function validates the form.
[docs for handleSubmit]https://react-hook-form.com/api/useform/handlesubmit/#main
I put handleSubmit(onSubmit)() in a try catch block but it is not catching the errors. The code continues and the email is sent. How can I stop the email from being sent, if there is a form validation error.
import React, { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { string, number, object, InferType } from "yup";
import { url } from "inspector";
import emailjs from "@emailjs/browser";
function onSubmit(values: Props) {}
type Props = InferType<typeof schema>;
const schema = object({
firstName: string().required("First name is required"),
lastName: string().required("Last name is required"),
});
function FormEmail() {
const form = useRef(null);
const [value, setValue] = useState<string | undefined>();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<Props>({
resolver: yupResolver(schema),
});
const sendEmail = (e: { preventDefault: () => void }) => {
e.preventDefault();
try {
handleSubmit(onSubmit)();
emailjs
.sendForm(
"service_ztay5wh",
"template_wcc4f29",
form.current!,
"aXbWTWKdwzgImlYqz"
)
.then(
(result: { text: any }) => {
console.log(result.text);
},
(error: { text: any }) => {
console.log(error.text);
}
);
} catch (e) {
return;
}
};
return (
<div>
<form onSubmit={sendEmail} ref={form}>
<h3>First Name</h3>
<input
id="firstName"
type="text"
{...register("firstName")}
/>
<span className="error">{errors?.firstName?.message}</span>
<h3>Last Name</h3>
<input
id="lastName"
type="text"
{...register("lastName")}
/>
<span className="error">{errors?.lastName?.message}</span>
<button className="" type="submit">
Submit
</button>
</form>
</div>
);
}
export default FormEmail;
Would really appreciate any help! Thanks!