Search code examples
reactjsreact-hooksmernreact-hook-formreact-fullstack

How to empty/clear a react form fields after passing form data to fire base data base?


I am validating and passing react form data to fire base data base through react hook form. It's validate and pass but form fields remain filled. I want after passing data to data base form fields will be empty/clear. So what should I do??There is which I try

import React from "react";
import "./App.css";
import { useForm } from "react-hook-form"; 
import classNames from "classnames";


function App() {
  const { register, handleSubmit,formState: { errors } } = useForm();

const onSubmit = async (data) => {
    console.log(data); 
    // send data to firebase API
    const responseRaw = await fetch(
      "https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      }
    );
    const response = responseRaw.json();
   
  };

There are many fields in my form but here I show some fileds

 <form name="Registration_form" id="Form" action="" method="POST" onSubmit={handleSubmit(onSubmit)}>
          
          <div className="form-group my-3">
            <label htmlFor="name">Name:</label>
           
            <input 
              type="text" 
              name="Name" 
              id="Name"
              className={classNames("form-control",{"is-invalid":errors.Name,})}  
              autoComplete="off" 
              {...register('Name', 
              { required: true,
                maxLength: 15,
                pattern: /^[A-Za-z]+$/
              
              })
              }

              
              />

            <span id="name" className="text-danger fw-bold">{errors.Name?.type === "required"  && "This field is required"}</span>

            <span id="name" className="text-danger fw-bold">{errors.Name?.type ==="maxLength" && "Length Should be less then 15"}</span>

            <span id="name" className="text-danger fw-bold">{errors.Name?.type === "pattern"  && "Digits are not allow"}</span>

          </div>

<div className="form-group my-3">
            <label htmlFor="email">Email: </label>
            
            <input 
              type="text" 
              name="email" 
              id="email"
              className={classNames("form-control",{"is-invalid":errors.email,})}  
              placeholder="[email protected]" 
              autoComplete="off" 
              {...register('email', 
              { 
                required: true,
                pattern:/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
                
              
              })
              }
            
              />

              <span id="mail" className="text-danger fw-bold">{errors.email?.type === "required"  && "Email is required"}</span>

              <span id="mail" className="text-danger fw-bold">{errors.email?.type === "pattern"  &&"Invalid format"}</span>

           
          </div>
<input type="submit" id="submit" value="submit"  className="btn btn-success my-3" />
        </form>

That is code which i try for validation and passing data to data base through react hook form. But no I stuck here how to empty/clear all form fields after passing data to data base?


Solution

  • There's a reset function inside useForm that you can use

    function App() {
      const {
        register,
        handleSubmit,
        formState: { errors },
        reset,
      } = useForm();
    
      const onSubmit = async (data) => {
        console.log(data);
        // send data to firebase API
    
        // call reset here
        reset();
      };
    }