Error: Uncaught TypeError: methods is nul
I used react hook form in my project like following:
import React from 'react';
import { useController, useForm } from 'react-hook-form';
interface formTypes {
fullname: string,
username: string,
email: string,
password: string,
confirmPassword: string,
phone: string,
gender: string,
countries: string
}
const NewForm = () => {
const { field } = useController({
name: 'fullname', rules: {
required: true,
pattern: /^[a-zA-Z0-9] $/i
}
})
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data: formTypes) => console.log(data);
console.log(errors);
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
{/* <input type="text" placeholder="username" {...register("username", {
required: true, maxLength: 15, pattern: /^[a-zA-Z0-9] $/i
})} /> */}
<input {...field} />
<input type="password" placeholder="password" {...register("password", { required: true, min: 4 })} />
<input type="password" placeholder="confirmPassword" {...register("confirmPassword", { maxLength: 5 })} />
<input {...register("gender", { required: true })} type="radio" value="male" />
<input {...register("gender", { required: true })} type="radio" value="female" />
<input type="email" placeholder="email" {...register("email", { pattern: /(^(([^<>()[\]\\.,;:\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,}))$)/i })} />
<input type="tel" placeholder="phone" {...register("phone", { pattern: /(^(\ 98|0)?\d{10}$)/i })} />
<select {...register("city")}>
<option value="tehran">tehran</option>
<option value="shiraz">shiraz</option>
<option value="tabriz">tabriz</option>
</select>
<input type="submit" />
</form>
</>
);
}
export default NewForm
i don't know why i receive the following error because i hadn't insert any data to my form (actually the page crashed because existing error) and it gives me an error. how can i solved it and how can use fom provider react-hook-form in my project?
Uncaught TypeError: methods is null
useController useController.ts:32
NewForm NewForm.tsx:17
React 12
workLoop scheduler.development.js:266
flushWork scheduler.development.js:239
performWorkUntilDeadline scheduler.development.js:533
js scheduler.development.js:571
js scheduler.development.js:633
factory react refresh:6
Webpack 24
NOTE: i write defaultValue but it still receive following error!
CodePudding user response:
You need to retrieve control
from useForm
hook and pass it to the useController
hook as a prop like this:
const {
control,
register,
handleSubmit,
formState: { errors }
} = useForm();
const { field } = useController({
control: control,
name: "fullname",
rules: {
required: true,
pattern: /^[a-zA-Z0-9] $/i
}
});
You can take a look at this sandbox for a live working example of your form.