Home > Software design >  How to pass an ID to a modal from a table row
How to pass an ID to a modal from a table row

Time:12-07

I'm trying to send some parameters in the body to my backend:

idTR
securityQuestion
secretAnswer

I have a table that contains some records and I put a button in each record that opens a Modal

Then two inputs are received in this modal and sent to the body in the request via a button inside the modal.

You have successfully sent the entries in modal. Everything works as it should in the background. I did not succeed in sending the ID, but I still need the id and I don't know how to pass it from the table to the modal.

  const TransferPoint = () => {
  const dispatch = useDispatch();
  const [transferPointList, lode, error, transferPointLists] = Transferpointhook();
  const [loading, setloading] = useState(true);
  const [modal, setModal] = useState(false);

  const {
    transferPointListss
  } = useSelector((state) => ({
    transferPointListss: state.TransferPoin.transferPointList,
  }));

  // validation
  const validation = useFormik({
    // enableReinitialize : use this flag when initial values needs to be changed
    enableReinitialize: true,
    initialValues: {
      idTR: "",
      securityQuestion: "",
      secretAnswer: "",
    },
    validationSchema: Yup.object({
      securityQuestion: Yup.number().required("Please Select Question"),
      secretAnswer: Yup.string().required("Please Answer"),
    }),
    onSubmit: (values) => {
      const updateTransfer = {
        idTR: "",
        securityQuestion: (Number(values["securityQuestion"])),
        secretAnswer: values["secretAnswer"],
      };
      setloading(true);
      // save new ticket
      dispatch(updateTransferPoint(updateTransfer));

      setloading(false);

      validation.resetForm();
      toggle();
    },
  });

  const toggle = useCallback((idd) => {
    console.log(idd)

    if (modal) {
      setModal(false);
    } else {
      setModal(true);
    }
  }, [modal]);


  useEffect(() => {
    if (modal === false) {
      dispatch(getTransferPointList());
    }
  }, [dispatch, modal]);

 return (
    <div>
      <Row>
        <Col xl={12}>
          <div className="table-responsive  mt-4 mt-xl-0">
            <Table className="table-success table-striped table-nowrap align-middle mb-0">
              <thead className="table-light ">
                <tr>
                  <th scope="col">account</th>
                  <th scope="col">point</th>
                  <th scope="col">date</th>
                  <th scope="col">isValidation</th>
                </tr>
              </thead>
              <tbody className="table-light">
                {!lode ? (
                  transferPointLists.data ? (
                    transferPointLists.data ? (
                      transferPointLists.data.map((item, index) => {
                        return (
                          <tr key={item.id}>
                            <td className="fw-medium">
                              {item.payeeId.username}
                            </td>
                            <td>{item.point}</td>
                            <td>{item.date}</td>
                            {item.isValidation ? (
                              <td>confirmed </td>
                            ) : (
                              <td>
                                <Button
                                  color="danger"
                                  className="rounded-pill add-btn"
                                  onClick={() => {  toggle(item.id); }}> emphasis
                                </Button>
                              </td>
                            )}
                          </tr>
                        );
                      })
                    ) : (
                      <div className="d-flex justify-content-center mx-2 mt-2">
                        {" "}
                        <Spinner color="primary"> Loading... </Spinner>
                      </div>
                    )
                  ) : (
                    <h4> no record</h4>
                  )
                ) : (
                  <Loader error={error} />
                )}
              
              </tbody>
            </Table>
          </div>
        </Col>
      </Row>

      <Modal
        isOpen={modal}
        toggle={toggle}
        centered
        size="lg"
        className="border-0"
        modalClassName="zoomIn"
      >
        <ModalHeader toggle={toggle} className="p-3 bg-soft-info">
          {"Add Ticket"}
        </ModalHeader>
        <Form
          className="was-validated"
          onSubmit={(e) => {
            e.preventDefault();
            validation.handleSubmit();
            return false;
          }}
        >
          <ModalBody>
            <Row className="g-3">
              <Col lg={12}>
                <div className="mb-3">
                  <Label htmlFor="validationLabel" className="form-label">
                  Security Question
                  </Label>
                  <select className="form-control is-invalid"
                  name="securityQuestion"
                  id="validationselect"
                  placeholder=""
                  onChange={validation.handleChange}
                  onBlur={validation.handleBlur}
                  value={validation.values.securityQuestion || ""}
                  required>

                  <option value="">Open this select menu</option>
                  <option value= "1" >One </option>
                  <option value="2">Two</option>
                  <option value="3">Three</option>
                </select>
                </div>
              </Col>
            </Row>

            <Row className="g-3">
              <Col lg={12}>
                <div className="mb-3">
                  <Label htmlFor="validationLabel" className="form-label">
                  secretAnswer
                  </Label>
                  <Input
                    className="form-control is-invalid"
                    name="secretAnswer"
                    id="validationInput"
                    placeholder=""
                    onChange={validation.handleChange}
                    onBlur={validation.handleBlur}
                    value={validation.values.secretAnswer || ""}
                    required
                  ></Input>
                </div>
              </Col>
            </Row>
          </ModalBody>
          <div className="modal-footer">
            <div className="hstack gap-2 justify-content-end">
              <button
                onClick={() => {
                  setModal(false);
                }}
                type="button"
                className="btn btn-light"
                data-bs-dismiss="modal"
              >
                Close
              </button>
              <button type="submit" className="btn btn-success" id="add-btn">
                {"Add Ticket"}
              </button>
            </div>
          </div>
        </Form>
      </Modal>
      <ToastContainer closeButton={false} />
    </div>
  );
};

export default TransferPoint;

CodePudding user response:

Maintain a useState for the id

const [selectedId, setSelectedId] = useState();

and update in click event

 const toggle = useCallback((idd) => {
    
   setSelectedId(did)
    ......
  • Related