繁体   English   中英

我想在 React.js 和 Mysql 的表单列(自动填充数据)中显示从 api 获取的数据

[英]I want to display fetched data from api in form columns (auto fill data) in React.js and Mysql

我在未提交表单的情况下使用 onKeyUp 事件触发 api,如果手机号码匹配,我成功获取数据作为响应。 但我不明白如何将这些数据显示为列中的默认值。 我也尝试在 useState 默认值中执行此操作,但它不起作用。

请帮我。 谢谢!

这是我的前端代码。

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

** 这是后端代码**

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);
  });
})
); ```

您直接在输入的 defaultValue 内发送数组。 输入的 defaultValue 需要一个文本。
如果要通过api更新defaultValue,下面是流程。

GetCustNameFill 的注释行const GetCustNameFill GetCustNameFill console.log 。
在 onKeyUp 函数内部使用setCustomerDataFill(Rres.data[0])

并将输入 defaultValue 变量从GetCustNameFillcustomerDataFill defaultValue={customerDataFill.Cust_Name}

我认为您不需要customerDataFill状态。
使用customerName状态就足够了。
如果已找到具有contactNouser且未设置customerName ,则更改您的OnKeyUpFunc以设置customerName

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);
      }
    });
};

最后,只保留emailWithTitle输入中的value

<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>

当您更改nameWithTitle值并且尚未设置emailWithTitle时,这应该作为自动完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM