Reputation: 57
this is my first time using hooks I don't know How can I clear input fields after submit, form.reset() doesn't work
import { useForm } from "react-hook-form";
import....
export default function AddUser() {
const URL = "http://localhost:3000/AddUser";
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
if (data) {
axios.post(URL, data);
}
form.reset()
};
here is the return part
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<div className="container">
<input type="text" name="name" placeholder="Name" ref={register({required: true})}/>
<input type="radio" name="gender" value="male" ref={register({ required: true })}/>:Male
<input type="radio" name="gender" value="female" ref={register({ required: true })}/:Female
<button type="submit" className="btn "> add</button>
</div>
</form>
);
}
thanks in advance
//////////
Upvotes: 1
Views: 13119
Reputation: 286
You need to set a default state to set when your click is handle, that way your component will reset on every submit. And yet, and if you wanna prevent default you must set event.preventDefault();
inside the onSubmit
function
import { useForm, useState } from "react-hook-form";
import....
export default function AddUser() {
const [formState, setFormState] = useState({})
const URL = "http://localhost:3000/AddUser";
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
if (data) {
setFormState(data)
axios.post(URL, formState);
}
form.reset()[![enter image description here][1]][1]
};
Upvotes: 2
Reputation: 216
You need to import reset
from useForm()
hook to be able to use it outside of your tags.
so
const { register, handleSubmit, errors, reset } = useForm();
then on your submit function
const onSubmit = (data) => {
if (data) {
axios.post(URL, data);
}
reset({})
};
Something along those lines should work.
Upvotes: 12