If a form submits successfully, I want the onSubmit
function to be called.
The validation is working correctly, but the onSubmit
function is not being called and there are no errors showing so I can not figure out the issue.
This is the onSubmit
function causing the problem:
const onSubmit: SubmitHandler<Props> = (data) => console.log("testing");
and I am calling it with this line:
<form onSubmit={handleSubmit(onSubmit)} ref={form}>
I am using the react-hook-form library and yup to validate forms. I am also using react, and typescript.
This is the rest of the code:
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";
type Props = InferType<typeof schema>;
const schema = object({
firstName: string().required("First name is required"),
});
function FormEmail() {
const form = useRef(null);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<Props>({
resolver: yupResolver(schema),
});
const onSubmit: SubmitHandler<Props> = (data) => console.log("testing");
return (
<div>
<form onSubmit={handleSubmit(onSubmit)} ref={form}>
<h3>First Name</h3>
<input
id="firstName"
type="text"
{...register("firstName")}
/>
<span className="error">{errors?.firstName?.message}</span>
<button className="" type="submit">
Submit
</button>
</form>
</div>
);
}
export default FormEmail;
[docs for handleSubmit]https://react-hook-form.com/api/useform/handlesubmit/#main
Thanks for the help :)
CodePudding user response:
just use handleSubmit in onSubmit and you have some problem in the code... so this code will be working with you
import React, { useRef, useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { string, number, object, InferType } from "yup";
function onSubmit(values: Props) {}
const schema = object({
firstName: string().required("First name is required")
});
type Props = InferType<typeof schema>;
function FormEmail() {
const form = useRef(null);
const {
register,
handleSubmit,
formState: { errors }
} = useForm<Props>({
resolver: yupResolver(schema)
});
const onSubmit: SubmitHandler<Props> = (data) => console.log("testing");
return (
<div>
<form onSubmit={handleSubmit(onSubmit)} ref={form}>
<h3>First Name</h3>
<input id="firstName" type="text" {...register("firstName")} />
<span className="error">{errors?.firstName?.message}</span>
<button className="" type="submit">
Submit
</button>
</form>
</div>
);
}
export default FormEmail;
CodePudding user response:
Your code is good, but you the sendEmail
function is registered to form submit instead of the testing one.
It should be just like you wrote it in the smaller snippet (this works for me):
<form onSubmit={handleSubmit(onSubmit)} ref={form}>