Home > Net >  How to post an object in a react class component
How to post an object in a react class component

Time:01-14

Here is my CustomerBill.js

      import React, { Component } from "react";
      import "bootstrap/dist/css/bootstrap.min.css";
      import axios from "axios";
      import $ from "jquery";
      import Box from "@mui/material/Box";
      import Button from "@mui/material/Button";
      import CustomerTable from "./table";

      class CustomerBill extends Component {
        constructor() {
          super();
          this.state = {
            Customer: "",
            customerTable: {
              index: Math.random(),
              id: "",
              paymentDescription: "",
              quantity: "",
              unitPrice: "",
            },
          };
          this.handleSubmit = this.handleSubmit.bind(this);
          this.handleChange = this.handleChange.bind(this);
        }
        handleChange = (e) => {
          if (
            ["id", "paymentDescription", "quantity", "unitPrice"].includes(
              e.target.name
            )
          ) {
            let customerTable = { ...this.state.customerTable };
            customerTable[e.target.dataset.id][e.target.name] = e.target.value;
          } else {
            this.setState({ [e.target.name]: e.target.value });
          }
        };

        addNewRow = () => {
          this.setState((prevState) => ({
            customerTable: [
              ...prevState.taskList,
              {
                index: Math.random(),
                id: "",
                paymentDescription: "",
                quantity: "",
                unitPrice: "",
              },
            ],
          }));
        };

        clickOnDelete(record) {
          this.setState({
            customerTable: this.state.customerTable.filter((r) => r !== record),
          });
        }
        handleSubmit(event) {
          event.preventDefault();
          const bill = {
            Customer: this.state.customerTable,
          };

          axios
            .post(`http://localhost:4000/customer/bill`, bill)
            .then((response) => {
              console.log(response.data);
              return $(".alert-success").show();
            });
          this.setState({
            Customer: "",
          });
        }

        render() {
          let { customerTable } = this.state;
          return (
            <div>
              <div className="container">
                <div className="form-div">
                  <h1>Customer Bill</h1>
                  <Box
                    component="form"
                    onSubmit={this.handleSubmit}
                    noValidate
                    sx={{ mt: 1 }}
                    onChange={this.handleChange}
                  >
                    <div className="row" style={{ marginTop: 20 }}>
                      <div className="col-sm-3"></div>
                      <div className="col-sm-12">
                        <div className="card">
                          <div className="card-header text-center">
                            Bill Description
                          </div>
                          <div className="card-body">
                            <div className="row">
                              <div className="col-sm-4"></div>
                            </div>
                            <table>
                              <thead>
                                <tr>
                                  <th className="text-center"> sN </th>
                                  <th className="text-center"> Id </th>
                                  <th className="text-center">
                                    Payment Description
                                  </th>
                                  <th className="text-center"> Quantity </th>
                                </tr>
                              </thead>
                              <tbody>
                                <CustomerTable
                                  id="customerTable"
                                  add={this.addNewRow.bind(this)}
                                  delete={this.clickOnDelete.bind(this)}
                                  customerTable={customerTable}
                                />
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </div>
                      <div className="col-sm-1"></div>
                    </div>
                    <Button type="submit" fullWidth sx={{ mt: 3, mb: 2 }}>
                      <span className="btn btn-warning btn-block form-control form-group">
                        Submit
                      </span>
                    </Button>
                  </Box>
                </div>
              </div>
            </div>
          );
        }
      }

      export default CustomerBill;

Here is the table.js

    import React from "react";

    const CustomerTable = (props, val, idx, post) => {
    return props.customerTable.map((val, idx, post) => {
        let id = `id-${idx}`,
        paymentDescription = `paymentDescription-${idx}`,
        quantity = `quantity-${idx}`,
        unitPrice = `unitPrice-${idx}`;
        return (
        <tr key={val.index}>
            <td>
            <input
                type="text"
                name="id"
                data-id={idx}
                id={id}
                className="form-control "
            />
            </td>
            <td>
            <input
                type="text"
                name="paymentDescription"
                id={paymentDescription}
                data-id={idx}
                className="form-control "
            />
            </td>
            <td>
            <input
                type="text"
                name="quantity"
                id={quantity}
                data-id={idx}
                className="form-control"
            />
            </td>
            <td>
            <input
                type="text"
                name="unitPrice"
                id={unitPrice}
                data-id={idx}
                className="form-control"
            />
            </td>
            <td>
            {idx === 0 ? (
                <button
                onClick={() => props.add()}
                type="button"
                className="btn btn-primary"
                >
                Add Row
                </button>
            ) : (
                <button
                className="btn btn-danger"
                onClick={() => props.delete(val)}
                >
                Delete Row
                </button>
            )}
            </td>
        </tr>
        );
    });
    };
    export default CustomerTable;
 

Am trying to post the customerTable object into Customer array. However, am getting Uncaught TypeError props.customerTable.map is not a function. How can i improve this code to be able to push the data to the customer array as an object. Thanks in advance

CodePudding user response:

Your customerTable prop is initialized as an object, not an array so you can't use map on it.

You should initialize it this way:

customerTable: [{
  index: Math.random(),
  id: "",
  paymentDescription: "",
  quantity: "",
  unitPrice: "",
}],

CodePudding user response:

Try to use Object.values()

Check the example below: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

  • Related