0

suppose i have a product data for sales which i put in a state

const [products, setProducts] = useState([])

 products= {
    'product_id':'1',
    'total':'100'
    }
setProducts(products)

i send this data to a view products component

<SalesViewProducts
            products={products}
            >
</SalesViewProducts>

where the view products, SalesViewProducts, component looks something like

const SalesViewProducts = (props) => {
  const dispatch = new useDispatch();
  const [inventoryData, setInventoryData] = useState([]);
  const [selectedProducts, setSelectedProducts] = useState();
  const [show, setShow] = useState(false);
  useEffect(() => {
    // var total = 0;
    // selectedProducts.forEach(element => {
    //   total+=element.total
    // });
    // props.calculateTotal(total)
  });

  const addProducts = (data) => {
    console.log(props.products);
  };

  return (
    <div>
      <Button
        variant="primary"
        size="lg"
        onClick={() => console.log(props.products)}
        // or
        onClick={()=>setShow(true)}
        style={{ width: "100%", marginBottom: "1rem" }}
      >
        ADD PRODUCTS
      </Button>
      <Table striped bordered hover variant="light">

      </Table>

      <InventoryModal
        modalShow={show}
        modalSetShow={setShow}
        addProducts={addProducts}
      ></InventoryModal>
    </div>
  );
};
export default SalesViewProducts;

emphasizing on the button "ADD PRODUCTS", when the onclick function of that button is just console.log(props.products), i get the data just fine from the props.

my issue now comes is this button is actually supposed to open a modal, in which that modal InventoryModal has a whole table of products in inventory and a button that calls a function in the SalesViewProducts component.

const InventoryModal = (props) => {
  const dispatch = new useDispatch();

  const gridRef = useRef();
  const [show, setShow] = useState(props.modalShow);
  const handleClose = () => props.modalSetShow(false);

  const [rowData, setRowData] = useState([]);
  const [columnDefs] = useState([
    { field: "id", width: 100, headerName: "ID" },
    {
      field: "product_name",
      width: 244,
      headerName: "Name",
      wrapText: true,
      autoHeight: true,
    },
    { field: "product_price", width: 110, headerName: "Price" },
    { field: "in_stock", width: 110, headerName: "Stock" },

    {
      field: "action",
      cellRenderer: (params) => (
        <strong>
          <Button
            variant="success"
            size="sm"
            onClick={() => {
              // console.log(params.data.product_name)
              var data = {
                product_id: params.data.id,
                quantity: 1,
                price: 0,
                total: 0,
                name: params.data.product_name,
              };
              props.addProducts(data);
            }}
          >
            Add
          </Button>
        </strong>
      ),
      cellRendererParams: {
        clicked: function (field) {
          alert(`${field} was clicked`);
        },
      },
    },
  ]);
  useEffect(() => {
    dispatch(getAllInventoryAction())
      .unwrap()
      .then((data) => {
        setRowData(data.inventoryData);
      });
  }, []);
  return (
    <Modal show={props.modalShow} onHide={handleClose} size="lg">
      <Modal.Header closeButton>
        <Modal.Title>Select Products</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div className="ag-theme-alpine" style={{ height: 650, width: "100%" }}>
          <AgGridReact
            ref={gridRef}
            rowData={rowData}
            columnDefs={columnDefs}
            pagination={true}
            // rowHeight={100}
          ></AgGridReact>
        </div>
      </Modal.Body>
    </Modal>
  );
};
export default InventoryModal;

now when i click the add button in the inventory modal, supposedly its supposed to call the parents addProducts function which console.log(props.products). but the result of calling this function is [], why is this so? wheh i call the addProducts function from within the component everything works fine, but when i call the addproducts function from the child component everything goes wrong.

kevin
  • 29
  • 1
  • 7
  • this seems to be happening because the add button is a part of aggrid, when i move the button out of aggrid with the same functions, everything works fine. why does it not work when its in aggrid? – kevin Sep 03 '22 at 06:30
  • can you add a link to codesandbox with your code? – Amit Khanna Sep 03 '22 at 06:34

1 Answers1

0

ive solved this problem after realizing the issue was with aggridreact. i had to pass my function to context and then call it through context for it to work. im referencing this stackoverflow question that helped me

react functional component with ag grid cannot call parent function via context

<AgGridReact
    ref={gridRef}
        rowData={rowData}
        columnDefs={columnDefs}
        pagination={true}
        context={props}
        // rowHeight={100}

        >
    </AgGridReact>

 setColumn([
        { field: 'id', width: 100, headerName:"ID"},
        { field: 'product_name',width:244, headerName: 'Name',wrapText: true, autoHeight: true,    },
        { field: 'product_price',width:110, headerName: 'Price' },
        { field: 'in_stock',width:110, headerName: 'Stock' },
      
        { field: 'action',
        cellRenderer: (params) => (
            <strong>
              <Button
                variant="success"
                size="sm"
                onClick={()=>{
                  params.context.products()
                 
                }}
              >
                Add
              </Button>
            </strong>
          ),
         },
      
      ])
kevin
  • 29
  • 1
  • 7