1

I've created a react form and I cant call the function handleSubmit on submitting the form, everything looks fine to me but I'm sure there's a basic mistake that I'm making. Here's the code

import React from "react";
import {useState} from "react";
import Button from "./Button";
function Form(){
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [subject, setSubject] = useState("");
    const [message, setMessage] = useState("");

    function handleSubmit(event){
        console.log("Worker");
        if(name===""||email===""||subject===""||message===""){
            event.preventDefault()
        }else{
             fetch("http://localhost:3000/formSubmit", {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
             },
                body: JSON.stringify({ 
                name: name,
                email:email,
                subject:subject,
                message:message
            })
        })
    }
}

return(
    <div id="contact" className="fade-bottom ">
        <div id="form">
            <form id="form-internal" onSubmit={handleSubmit}>
                <h3 id="form-head">Contact Me!</h3>
                <input className="input-text" type="text" min={3} max={50} size={16} placeholder="Name"    value={name} onChange={(e) => setName(e.target.value)} />
                <input className="input-text" type="text" min={8} max={30} size={16} placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
                <input className="input-text" type="text" min={1} max={30} size={16} placeholder="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} />              
                <textarea id="message" min={1} max={300} size={34} type="text" placeholder="Message" value={message} onChange={(e) => setMessage(e.target.value)} />                   
                <input type="submit" id="submit-form" placeholder="Submit"/>
            </form>
        </div>
        </div>
     );
  }
export default Form;

"Worker" isnt being printed.

I have tried using other similar approaches like making it

const handleSubmit = (event)=>{.....}

and used async and even without it, can't get it to work

Abhishek
  • 11
  • 1
  • try calling the function like this onSubmit={(e)=>handleSubmit(e)} – Mel Carlo Iguis Feb 11 '23 at 04:12
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 11 '23 at 05:53

2 Answers2

0

you should call event.preventDefault() first, it basically default action that belongs to the event will not occur. Every time handleSubmit is called your app is rerendered, so to avoid this, you need to call it at first refer here https://stackoverflow.com/a/28480839/10220184

function handleSubmit(event){

        event.preventDefault() // here
        console.log("Worker");

        if(name===""||email===""||subject===""||message===""){
            alert('Enter all values') // some action you wanted
        }else{
             fetch("http://localhost:3000/formSubmit", {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
             },
                body: JSON.stringify({ 
                name: name,
                email:email,
                subject:subject,
                message:message
            })
        })
    }
Faiz Hameed
  • 488
  • 7
  • 15
  • Tried this and now page isnt reloading, but "Worker" is still not being printed in the console due to which I suspect my backend call to localhost:3000 is not taking place at all. Can you maybe suggest me a different approach for making this backend call that takes place on submitting the form. – Abhishek Feb 11 '23 at 06:19
0

Try onSubmit={(event) => handleSubmit(event)} and use FormData To submit

import React from "react";
import {useState} from "react";
import Button from "./Button";
function Form(){
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [subject, setSubject] = useState("");
    const [message, setMessage] = useState("");

    function handleSubmit(event){
        event.preventDefault()
        console.log("Worker");
        if(name===""||email===""||subject===""||message===""){
            console.log("Fill All Fields")
        } else{
            let formData = new FormData();
            formData.append('name', name);
            formData.append('email', email);
            formData.append('subject', subject);
            formData.append('message', message);

            fetch("http://localhost:3000/formSubmit", {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: formData,
            })
        }
    }

return(
    <div id="contact" className="fade-bottom ">
        <div id="form">
            <form id="form-internal" onSubmit={(event) => handleSubmit(event)}>
                <h3 id="form-head">Contact Me!</h3>
                <input className="input-text" type="text" min={3} max={50} size={16} placeholder="Name" required value={name} onChange={(e) => setName(e.target.value)} />
                <input className="input-text" type="text" min={8} max={30} size={16} placeholder="Email" required value={email} onChange={(e) => setEmail(e.target.value)} />
                <input className="input-text" type="text" min={1} max={30} size={16} placeholder="Subject" required value={subject} onChange={(e) => setSubject(e.target.value)} />              
                <textarea id="message" min={1} max={300} size={34} type="text" placeholder="Message" required value={message} onChange={(e) => setMessage(e.target.value)} />                   
                <input type="submit" id="submit-form" placeholder="Submit"/>
            </form>
        </div>
        </div>
     );
  }
export default Form;
Shariq Shahid
  • 272
  • 12