Search code examples
javascriptnode.jsreactjsform-datamern

How to use setformdata to store data in form


I'm making a form and below is the format. As you can see I was in two cases (for storing in multistage form) and upon clicking next on the second form we call {onSubmitform}. The problem which you can see is while entering data in form, I'm facing where to store it i.e, {onChange}. Also ~ please let me know if this was {onSubmitform} will work to send data to the backend.

import React, { useEffect, useState } from 'react';
const  Rider_Signup = ()=>{
    const [step, setstep] = useState(1);
    const [formdata, setFormData] = useState({zipcode:"", email:"",name:"",location:"", dob:"",phone:"",sex:"", password:"",aadhar:""}); // use to hold input from user 
    const onSubmitform = async e =>{
        e.preventDefault();
        try{
 
            const email=formdata.email;
            console.log(email);

            const body={email};

            const response = await fetch("http://localhost:5000/api/service/signup",{
                method:"POST",headers:{"Content-Type":"application/json"},
                body:JSON.stringify(body)
            })
            const datainjson = await response.json();

            window.location =`/driver/login`;

        }catch(err){
            console.log('Error')
        }

    }
    const renderForm = () =>{
    switch(step){
        case 1: return <div className="admin_form_div">
        <h1 className="form_header">Hey ! </h1>
    
        <center>
            <form  action="/initial" id="admin_form"  name="admin_form">
                <label for="Email" className="label">Enter the Email</label><br/>
                <input type="email" name="name" className="Email" value={formdata.email} onChange={e =>{console.log(formdata.email)
                    setFormData(formdata.email=(e.target.value))}} placeholder="email@id.com" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Please enter valid email" required />
                <br/>
                <br/>


                <button onClick = {() => setstep(step+1)}>Submit</button>

        </form> 
        </center>




    </div>
        case 2: return <div><h1>{formdata.email} </h1><button onClick = {() => setstep(step+1)}>Submit</button></div>
        default: return <div> {onSubmitform}</div>


    }

}
return (

    renderForm()
)
  
};
 
export default Rider_Signup;

Solution

    • formdata is const and cant be reassigned,
    • formdata can only be changed with setFormData hook.
    • ...formdata will save other fields when only the email is changing.
    • also, this is duplicated.
    onChange={
        e => {
            console.log(formdata.email)
            setFormData({ ...formdata, email: e.target.value })
        }
    }