Home > Software engineering >  how to pass useState variable value to array of object field for INSERT data react.js and mysql?
how to pass useState variable value to array of object field for INSERT data react.js and mysql?

Time:05-24

**I have a billing form and in this i have some product details that admin can fill these details but 1 field called "BillID" i want to directly pass a variable to it that contain 'Bill ID 1' value as a default value.

**This is My Code:-

  const [BillIdFetch, setBillIdFetch] = useState();

 useEffect(() => {
    axios.get("http://localhost:5000/getLastBill_Id").then(( res ) => {
      setBillIdFetch(res.data[0].Bill_Id   1);
    });
  }, []);

 console.log("===>>>> Testing BillIdFetch ",BillIdFetch) //**I check in this variable value stored perfectly.

const [Product_Details, setProduct_Details] = useState([
    {
      index: Math.random(),
      billId : BillIdFetch, //**I want 'BllIdFetch' value pass to this state variable.
      prodId: "",
      qty: "",
      price: "",
      prod_SrNo: "",
      discount_price: "",
      proData_warranty: "",
    },
  ]);

In 'BillIdFetch' i got correct id 1 value and i also use this value for displaying Bill no. in form column. but when i set this value to 'billId' it shows like this :- {billId: undefined}

This is post request to the server.

In this a pass 'Produt_Details' array of object to it.

 const config = {
        header: {
          "Content type": "appication/json",
        },
      };

      const { data } = await axios.post(
        "http://localhost:5000/billing_data",
        { p_value: Product_Details },
        config
      );

CodePudding user response:

What you need to do is to check when BillIdFetch changes, and then set the correct state value for Product_Details. In your current code, the code for setting the value of Product_Details? will run before the fetching.

To solve this, use a useEffect hook with BillIdFetch as a dependency, thus, this code will run when BillIdFetch changes.

It could look something like this:

const [Product_Details, setProduct_Details] = useState([]);
const [BillIdFetch, setBillIdFetch] = useState();

useEffect(() => {
   axios.get("http://localhost:5000/getLastBill_Id").then(( res ) => {
     setBillIdFetch(res.data[0].Bill_Id   1);
   });
}, []);

useEffect(() => {
    if (billIdFetch === undefined) return;
    setProduct_Details([{
      index: Math.random(),
      billId : BillIdFetch,
      prodId: "",
      qty: "",
      price: "",
      prod_SrNo: "",
      discount_price: "",
      proData_warranty: "",
    }])
}, [billIdFetch])
  • Related