Passing multiple object data in an array dynamically and which will be changable

18 views Asked by At

I was working on an inventory management system, where i will be posting an object of data to an API endpoint. the data structure is as follows: { "date": "2023-09-18", "purchase_items": [ { "product": 0, "quantity": 2147483647, "price": "-" } ] } here i am getting the data of product from another api, in a dropdown. when i will select a product each time, in onChange function it will return jsx containing the product, quantity and price. where the quantity and price will be changeable. i am working with nested serializer first time, and can't understand how to do it properly. here is how i tried it

import { useState, useEffect } from "react";
import Dropdown from "../../components/Dropdown/Dropdown";
import InputComponent from "../../components/Input/Input";
import axiosInstance from "../../components/API/AxiosInstance";

const Test = () => {
  const token = `Token ${localStorage.getItem("token")}`;

  
  const [addNewData, setAddNewData] = useState({
    date: "",
    purchase_items: [],
  });

  // getting product data
  const [productData, setProductData] = useState([]);
  useEffect(() => {
    const fetchProductData = async () => {
      try {
        const response = await axiosInstance.get(
          "/v1/inventory/admin/product/",
          {
            headers: { Authorization: token },
          }
        );
        setProductData(response.data.results);
      } catch (err) {
        console.log(err);
      }
    };
    fetchProductData();
  }, [token]);

  // handeling input data
  const handleInputChange = (name, value) => {
    setAddNewData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  // handeling input data for purchase_items
  const updateProductQuantityPrice = (productId, quantity, price) => {
    const updatedPurchaseItems = addNewData.purchase_items.map((item) => {
      if (item.product.id === productId) {
        return {
          ...item,
          quantity,
          price,
        };
      }
      return item;
    });

    setAddNewData((prevData) => ({
      ...prevData,
      purchase_items: updatedPurchaseItems,
    }));
  };

  // handeling product
  const handleProduct = (productId) => {
    const isProductInPurchaseItems = addNewData.purchase_items.some(
      (item) => item.product.id === productId
    );

    const selectedProduct = null;

    if (!isProductInPurchaseItems) {
      selectedProduct = productData.find((product) => product.id === productId);
    }

    // Create a new purchase item object
    const newPurchaseItem = {
      product: selectedProduct,
      quantity: 0,
      price: "0",
    };

    // Update the purchase_items array
    setAddNewData((prevData) => ({
      ...prevData,
      purchase_items: [...prevData.purchase_items, newPurchaseItem],
    }));
    console.log("Selected Product:", newPurchaseItem.product);
    console.log("Price:", newPurchaseItem.price);
    console.log("Quantity:", newPurchaseItem.quantity);
  };

  return (
    <form className="p-5">
      <div className="row mb-3">
        <div className="col-md-6">
          <InputComponent
            type="date"
            id="purchaseDate"
            placeholder="Date"
            value={addNewData.date}
            onChange={(value) => handleInputChange("date", value)}
          />
        </div>

        <div className="col-md-6">
          <Dropdown
            label="Product"
            options={[
              { value: null, title: "Select an item", disabled: true },
              ...productData.map((item) => ({
                value: item.id,
                title: item.product_name,
              })),
            ]}
            onChange={handleProduct}
          />
        </div>

        {addNewData.purchase_items.map((item, index) => (
          <div className="row" key={index}>
            <div className="col-md-4">
              <InputComponent value={item.product} disabled={true} />
            </div>
            <div className="col-md-4">
              <InputComponent
                value={item.quantity}
                onChange={(value) =>
                  updateProductQuantityPrice(item.product.id, value, item.price)
                }
              />
            </div>
            <div className="col-md-4">
              <InputComponent
                value={item.price}
                onChange={(value) =>
                  updateProductQuantityPrice(
                    item.product.id,
                    item.quantity,
                    value
                  )
                }
              />
            </div>
          </div>
        ))}
      </div>
    </form>
  );
};

export default Test;
0

There are 0 answers