I have an email contact form, and now I want to implement validation with React Hook Form and Zod. This seems a lot thougher as I was hoping for.
This is my email send function that get’s called when the contact form is submitted:
const handleSubmitForm = async (e: React.FormEvent<HTMLFormElement>) => {
const formData = new FormData(e.currentTarget)
const { fullName, senderEmail, phone, message } = Object.fromEntries(formData)
const finalHtml = render(
<ContactFormEmail message={message as string} senderEmail={senderEmail as string} />,
{
pretty: true
}
)
const finalText = render(
<ContactFormEmail message={message as string} senderEmail={senderEmail as string} />,
{
plainText: true
}
)
try {
const res = await fetch('/api/sendEmail.json', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: '[email protected]',
to: '[email protected]',
subject: 'new message from contact form',
reply_to: senderEmail,
html: finalHtml,
text: finalText
})
})
} catch (error: any) {
setError('root', {
message: error.response.data.message
})
}
}
I want to call this method when the form is submitted, and also invoke React Hook Form validation at the same time.
I tried to integrate React Hook Form by calling this function like this:
handleSubmit(handleSubmitForm)
But that does not work and TypeScript is complaining:
“Argument of type ‘(e: React.FormEvent) => Promise’ is not assignable to parameter of type ‘SubmitHandler’.
Types of parameters ‘e’ and ‘data’ are incompatible.
Type ‘FormData’ is missing the following properties from type ‘FormEvent’: nativeEvent, currentTarget, target, bubbles, and 11 more.ts(2345)”
Does someone know how I can call handleSubmitForm when submitting the the form and invoke React Hook Form at the same time?
Thanks a lot for your help,
Anthony