Skip to content
Advertisement

How can validate and send react form data to fire base data base?

I try it but not working

    import React from "react";
    import "./App.css";
    import { useForm } from "react-hook-form"; 
    import classNames from "classnames";
    import { useState } from "react";
    
    
    
    function App() {
      const { register, handleSubmit,formState: { errors } } = useForm();
      // console.log(errors);
      const onSubmit = data => console.log(JSON.stringify(data));


const postData = async (e)=>{
    e.preventDefault();
    const res = await fetch("https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
    {
      method:"POST",
      header:{
        "content-type":"application/json",

      },

Here what I pass in body?

 body:JSON.stringify(data)
    }
    
    )
  };

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

return (
    <div>

<div className="container">
      
      <div className="form-group my-3 ">
        <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>
      <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@example.com" 
          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" onClick={postData} className="btn btn-success my-3" />
        </form>

That is code which I try but it not working anybody review it and give your valuable comments and suggestions Basically I want form validation using react hook form,its done but when I stuck in passing data to fire base data base when I use, useState then its override because react hook form already store it but how to pass it to data base with out useState?? Through react hook form

Advertisement

Answer

You should remove your onClick from the submit button and handle your form submission from the onSubmit event on the form. Send your form data to your firebase endpoint, from your onSubmit function like so.

<input type="submit" id="submit" value="submit" onClick={postData}  <-- Remove this
className="btn btn-success my-3" />

const onSubmit = (data) => {
    // All your form fields will the converted to json object (data)
    // and will be handled by hooks form
    console.log(data); 
    // send data to firebase API
    const responseRaw = fetch(
      "https://your-firebase-url",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      }
    );
    const response = responseRaw.json();
   
  };
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement