post data using form works, but fetch API's not working in my case

Viewed 555

I am working on React Project, currently making a signup form.
Posting Form Data using Form works fine. But when i use onSubmit={handleSubmit}and use fetch API's like axios or just fetch, it stuck at axios.post(url,options). I actually need to Post Users data and if User already exist than need to print error message at client side.
Register Component 1:

<Form method='POST' action="http://localhost:5000/api/register">
            <Form.Group  controlId="validationCustom01">
              <Form.Label>Full Name</Form.Label>
              <Form.Control
                 type="text"
                 placeholder="Full Name"
                />
                <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
            
            <Form.Group controlId="validationCustomUsername">
                 <Form.Label>Username</Form.Label>
                <InputGroup >
                    <Form.Control
                        type="email"
                        placeholder="Email"
                        name="email"
                    />
                </InputGroup>
            </Form.Group>
                <Form.Group controlId="validationCustom04">
                    <Form.Label>Password</Form.Label>
                    <Form.Control 
                    type="password" 
                    placeholder="Password"
                    name="password" />
                </Form.Group>
        <Button type="submit" className='button bg-success' >Submit</Button>
    </Form>  

Server.js

app.post('/api/register', async (req,res) => 
    {
        let {name,email,password} =req.body
         if(password.length >=8 )
         {
            let hashpassword = await bcrypt.hash(password,10);
            pool.query(`SELECT * FROM USERSDATA WHERE EMAIL= $1 `, [email],
                 (err,results) =>
                     {
                         if(err){
                             throw err;
                         };
                         if(results.rows.length == 0)
                         {
                             pool.query(`INSERT INTO USERSDATA (NAME,EMAIL,PASSWORD) VALUES ($1,$2,$3) RETURNING id`,[name,email,hashpassword],
                             (err,results) => 
                             {
                                 if(err)
                                 {
                                     throw error;
                                 }
                                 res.redirect("http://localhost:3000/login");
                             }
                              );
                         }
                         else{
                             res.status(400) 
//Here i want to send error as response and to process this error at frontend
                             res.redirect("http://localhost:3000/register")
                         }
                      }
                     );
         }
    });

i tried to handle the Form submit using handleSubmit and made different fetch post requests but got different type of error while playing with the code. One of technique i used is given.

const handleSubmit = async e => {
 e.preventDefault()
const options = {
method: "POST",
body:JSON.stringify(data),
headers:{
'Content-Type':'application/json'}}

    const res = await axios.post('/api/register', options) 
// here (above) i got many errors while playing different techniques like different fetch API's

  }}
return(
<Form onSubmit={handleSubmit} > 
...
...
</Form>
)

Is there any other way i can access server response message in React Component? As this took my 8 hours and still is unsolved.

2 Answers
const res = axios.post('/api/register', options) 

i think you are missed to use await before axios post call

add await to the post calll

const res = await axios.post('/api/register', options) 

What you want is to transform this form into a react component? The best way to do it is to control field into state after that you could sent it via axios in the click of your submit button

Something like this:

import React, { useState } from "react";
import { Form, InputGroup, Button } from "react-bootstrap";
import axios from "axios";

const getInitialState = () => ({
  name: "",
  email: "",
  password: ""
});

export default function App() {
  const [formData, setFormData] = useState(getInitialState());
  const handleSubmit = async (data) => {
    const options = {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json"
      }
    };
    return axios.post("/api/register", options);
  };

  const handleChange = (field) => (e) => {
    const { value } = e.target;
    setFormData({
      ...formData,
      [field]: value
    });
  };

  return (
    <Form
      onSubmit={(e) => {
        e.preventDefault();
        handleSubmit(formData);
      }}
    >
      <Form.Group controlId="validationCustom01">
        <Form.Label>Full Name</Form.Label>
        <Form.Control
          type="text"
          placeholder="Full Name"
          value={formData.name}
          onChange={handleChange("name")}
        />
      </Form.Group>

      <Form.Group controlId="validationCustomUsername">
        <Form.Label>Username</Form.Label>
        <InputGroup>
          <Form.Control
            type="email"
            placeholder="Email"
            name="email"
            value={formData.email}
            onChange={handleChange("email")}
          />
        </InputGroup>
      </Form.Group>
      <Form.Group controlId="validationCustom04">
        <Form.Label>Password</Form.Label>
        <Form.Control
          type="password"
          placeholder="Password"
          name="password"
          value={formData.password}
          onChange={handleChange("password")}
        />
      </Form.Group>
      <Button type="submit" className="button bg-success">
        Submit
      </Button>
    </Form>
  );
}
Related