Home > other >  I want to display fetched data from api in form columns (auto fill data) in React.js and Mysql
I want to display fetched data from api in form columns (auto fill data) in React.js and Mysql

Time:05-15

i am using onKeyUp event for fire api without submitting the form and i fetched data in response successfully if Mobile number matched. But i don't understand how to display these data as a default value in columns. i also try to do this in useState default value but it doesn't work.

Please help me. Thank you!

Here is my code of frontend.

import React, { useEffect, useState } from 'react'
import { Alert } from 'react-bootstrap';
import { useForm } from 'react-hook-form';

const Billing = () => {

    const [fill, setFill] = useState(false);
    const [success, setSuccess] = useState(false);
    const [customerDataFill, setCustomerDataFill] = useState()
  
    const {
      register,
      handleSubmit,
      formState: { errors },
    } = useForm();

   

    const [bill, setBill] = useState({
      contactNo: "",
     
    });

    const OnKeyUpFunc = () =>{
      const { contactNo } = bill; 
  
          axios.post("http://localhost:5000/getCustomerDetails", {
            contactNo: contactNo,
          })
          .then((Rres) => {
            setCustomerDataFill(Rres.data)
            console.log(Rres.data, "<<<<-----This is customer details testing...");
          }); 
      }


//**I WANT TO DISPLAY THIS FETCHED CUSTOMER NAME IN CUSTOMER NAME COLUMN**

      const GetCustNameFill = customerDataFill && customerDataFill.map((cData) => cData.Cust_Name)


      const [customerName, setcustomerName] = useState("")
      console.log(GetCustNameFill,"----<><><> GetCustNameFill fetch name checking")

    const handleCustNameChange = (e) => {
      setcustomerName(e.target.value);
      // console.log(e, "this is e check...");
    };

    let name, value;
    const handleInputs = (e) => {
      console.log(e);
      name = e.target.name;
      value = e.target.value;
  
      setBill({ ...bill, [name]: value });
      setFill(false);
    };
  
    const onclick = async (e) => {
      // e.preventDefault();
      const {  contactNo  } =
        bill;
  
      try {
        if (
            customerName === "" ||
            contactNo === "" 
            
        ) {
          setFill(true);
          setSuccess(false);
        } else {
          setFill(false);
          const config = {
            header: {
              "Content type": "appication/json",
            },
          };
  
          const { data } = await axios.post(
            "http://localhost:5000/billing_data",
            {   
              cust_name : customerName,
              contact_no : contactNo,
             
            },
            config
          );
  
          console.log(data);
          localStorage.setItem("Billing_details", JSON.stringify(data));
          setSuccess(true);
        }
      } catch (error) {
        console.log(error);
      }
    };

return ( <>

    <div className="modal fade" id="modalCenter" tabindex="-1" aria-hidden="true">
                          <div className="modal-dialog modal-dialog-centered modal-lg" role="document">
                            <div className="modal-content">
                              <div className="modal-header">
                                <h5 className="modal-title" id="modalCenterTitle">Bill information</h5>
                                <button
                                  type="button"
                                  className="btn-close"
                                  data-bs-dismiss="modal"
                                  aria-label="Close"
                                ></button>
                              </div>

                              <form onSubmit={handleSubmit(onclick)} method="POST">
                  {fill && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong > Please Fill All the Required Field!</strong>
                      </Alert>
                    </div>
                  )}

                  {success && (
                    <div className="container mt-3">
                       <Alert variant="success" style={{ fontSize: 15 }}>
                        <strong style={{color:"green"}}>Bill Added Successssfully!</strong>
                      </Alert>
                    </div>
                  )}

                  {errors.contact && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong>{errors.contact.message}</strong>
                      </Alert>
                    </div>
                  )}
                  
                  {errors.email && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong>{errors.email.message}</strong>
                      </Alert>
                    </div>
                  )}
                              <div className="modal-body">
                              <div className="row  g-2">
                              <div className="col mb-2">
                                    <label for="nameWithTitle" className="form-label">Contact No.</label>
                                    <input
                                      type="text"
                                      id="nameWithTitle"
                                      className="form-control"
                                      placeholder="Enter Contact no."
                                      value={bill.contactNo}
                                      onChange={handleInputs}
                                      name="contactNo"
                                      onKeyUp={OnKeyUpFunc}
                                    />
                                  </div>

                              <div className="col mb-2">
                                    <label for="emailWithTitle" className="form-label">Customer name</label>
                                    <input
                                      type="text"
                                      id="emailWithTitle"
                                      className="form-control"
                                      placeholder="Enter Customer Name"
                                      value={customerName}
                                      onChange={handleCustNameChange}
                                      defaultValue={GetCustNameFill}
                                    />
                                  </div>

                                 
                                </div>

                               


                              </div>
                              <div className="modal-footer">
                                <button type="button" className="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" className="btn btn-primary">submit</button>
                              </div>
                             </form>
                            </div>
                          </div>
                        </div>
  </>
  )
}

export default Billing

** Here is Backend Code**

var express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mysql = require("mysql");
const expressAsyncHandler = require("express-async-handler");
const generateToken = require("./jwtToken/generateToken");
const bcrypt = require("bcryptjs");

const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "star_battery_db",
});

db.connect((err) => {
  if (err) {
    console.warn("Error in connection, Check XAMPP server");
  } else {
    console.warn("MySql db connected");
  }
});

app.use(cors());
app.use(express.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(5000, () => console.log("Server is running on 5000"));

// Api for fetch Partcular customer data for billing.
app.post("/getCustomerDetails",expressAsyncHandler(async (req, res) => {
  const contactNo = req.body.contactNo

  const users = `SELECT * FROM cust_master WHERE Contact= ${db.escape(contactNo)}`;
  db.query(users, (err, result) => {
    if (err) {
      res.status(404).send(err);
    }
    res.status(201).send(result);
  });
})
); ```

CodePudding user response:

You are directly sending the array inside the defaultValue of input. The defaultValue for input is expecting a text.
If you want to update the defaultValue through api below is the process.

Comment line const GetCustNameFill and console.log for GetCustNameFill.
Inside onKeyUp function use setCustomerDataFill(Rres.data[0]);

and change the input defaultValue variable from GetCustNameFill to customerDataFill. defaultValue={customerDataFill.Cust_Name}

CodePudding user response:

I think that you don't need the customerDataFill state.
Using the customerName state should be enough.
Change your OnKeyUpFunc to set the customerName if a user with contactNo has been found and customerName was not set:

const [customerName, setcustomerName] = useState('');

const OnKeyUpFunc = () => {
  const { contactNo } = bill;

  axios
    .post('http://localhost:5000/getCustomerDetails', {
      contactNo: contactNo,
    })
    .then(({ data }) => {
      // If at least a user with `contactNo` has been found, set `customerName`
      if (data.length) {
        setcustomerName(data[0].Cust_Name);
      }
    });
};

Finally, keep only the value in the emailWithTitle input:

<div className="col mb-2">
  <label for="emailWithTitle" className="form-label">Customer name</label>
  <input
    type="text"
    id="emailWithTitle"
    className="form-control"
    placeholder="Enter Customer Name"
    value="{customerName}"
    onChange="{handleCustNameChange}"
  />
</div>

This should work as an autocomplete when you change your nameWithTitle value and emailWithTitle has not been set.

  • Related