简体   繁体   English

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

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

i am using onKeyUp event for fire api without submitting the form and i fetched data in response successfully if Mobile number matched.我在未提交表单的情况下使用 onKeyUp 事件触发 api,如果手机号码匹配,我成功获取数据作为响应。 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.我也尝试在 useState 默认值中执行此操作,但它不起作用。

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

You are directly sending the array inside the defaultValue of input.您直接在输入的 defaultValue 内发送数组。 The defaultValue for input is expecting a text.输入的 defaultValue 需要一个文本。
If you want to update the defaultValue through api below is the process.如果要通过api更新defaultValue,下面是流程。

Comment line const GetCustNameFill and console.log for GetCustNameFill . GetCustNameFill 的注释行const GetCustNameFill GetCustNameFill console.log 。
Inside onKeyUp function use setCustomerDataFill(Rres.data[0]) ;在 onKeyUp 函数内部使用setCustomerDataFill(Rres.data[0])

and change the input defaultValue variable from GetCustNameFill to customerDataFill .并将输入 defaultValue 变量从GetCustNameFillcustomerDataFill defaultValue={customerDataFill.Cust_Name}

I think that you don't need the customerDataFill state.我认为您不需要customerDataFill状态。
Using the customerName state should be enough.使用customerName状态就足够了。
Change your OnKeyUpFunc to set the customerName if a user with contactNo has been found and customerName was not set:如果已找到具有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);
      }
    });
};

Finally, keep only the value in the emailWithTitle input:最后,只保留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>

This should work as an autocomplete when you change your nameWithTitle value and emailWithTitle has not been set.当您更改nameWithTitle值并且尚未设置emailWithTitle时,这应该作为自动完成。

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

相关问题 REACT.js 中的动态路由使用从 API 获取的数据 - Dynamic Routing in REACT.js using data fetched from an API 如何使用从 API 获取的数据填写表格? - How to fill a form with fetched data from an API? react.js:获取的数据在 api 文件夹之外未定义 - react.js : fetched data is undefined outside of api folder 想要使用 React.js 的材料 UI 在可折叠表中填充 state 中的行和列的动态数据 - Want to populate dynamic data for rows and columns from state in Collapsible table using material UI for React.js 如何获取API数据并在react.js中以表格形式显示 - How to fetch API data and show that on table form in react.js 如何在 React.js 中使用获取的数据过滤数组? - How to filter an array with fetched data in React.js? 如何在反应表中显示从 API 获取的数据? - How to display fetched data from API in react-table? 如何正确显示从 api 获取的数据? - How can display data fetched from an api properly in react? 如何在React.js前端应用程序中显示来自Rails 5 API的数据? - How to display data from Rails 5 API in React.js frontend app? React.js-从API中获取数组数据并在其上添加一个#号以形成十六进制颜色 - React.js - Taking array data from an API and ammending a '#' to it to form a hex color
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM