简体   繁体   中英

How can I reset form after submit in reactjs hooks

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

//////////

这是我使用 form.reset() 时的错误

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.

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]
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM