Skip to content
Advertisement

delete button does not read id if modal added in ReactJS

I have created a CRUD application and successfully it is performing all the operations.

But when I try to create a modal so that it shows up a warning either to delete the id or not on clicking delete. And If I try to delete a particular id from the modal I’m unable to delete the selected item, else it is deleted the latest id in the list.

What might be the problem that is making me not delete a particular id from the list only when creating a modal.

Help me how I can make it work.

This is the button to open the warning modal:

const [open, setOpen] = useState(false);

const toggle = () => setOpen(!open);

<button onClick={toggle}>
    <MdIcons.MdDelete color='black' fontSize="1.3rem"/>delete</button>

This is the modal that opens after clicking delete:

<Modal isOpen={open} toggle={toggle}>
  <ModalHeader toggle={toggle}>Warning</ModalHeader>
    <ModalBody>Are you sure to delete this id from the list...</ModalBody>
   <ModalFooter>
     <Button onClick={() => onDelete(data.id)}>YES</Button>
     <Button onClick={toggle}>Cancel</Button>
   </ModalFooter>
</Modal>

In the above modal I have give the onclick event for button YES to delete the id selected, but the delete functionality is not working when I use it on a modal.

These are the button functionalities:

const getData = () => {
        axios.get(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`)
            .then((getData) => {
                setAPIData(getData.data);
            })
    }

    const onDelete = (id) => {
        axios.delete(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud/${id}`)
        .then(() => {
            getData();
        })
    }

Please help me how I can achieve the functionality of deleting the particular id after modal opens, and let me know if you need any more details regarding my code.

Advertisement

Answer

I am new to react, i don’t know if my explanation will be correct, my theory is that the problem was this: You were rendering the modal for every record, and only the last modal remained.

I put the modal outside the loop, and i declared a useState to track the selected id to delete, it worked =D

Read.js :

import axios from "axios";
import React, { useEffect, useState } from "react";
import { Table, Button, List, Popup, Grid, Icon, Dropdown, Menu, Header } from "semantic-ui-react";
import { useNavigate, Link } from "react-router-dom";
import * as MdIcons from "react-icons/md";
import * as AiIcons from "react-icons/ai";
import * as FiIcons from "react-icons/fi";
import { Modal, ModalFooter, ModalHeader, ModalBody } from "reactstrap";
import SideMenu from "../SideMenu/SideMenu";

function Read() {
  const [APIData, setAPIData] = useState([]);
  const [idToDelete, setIdToDelete] = useState(0);

  useEffect(() => {
    axios.get(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`).then((response) => {
      console.log(response.data);
      setAPIData(response.data);
    });
  }, []);

  const setData = (data) => {
    let {
      id,
      image,
      companyName,
      email,
      companyNumber,
      uniqueNumber,
      lineofBusiness,
      companyRevenue,
      openingTime,
      closingTime,
      discount,
      rating,
      address1,
      address2,
      pincode,
      area,
      city,
      state,
      country,
    } = data;

    localStorage.setItem("ID", id);
    localStorage.setItem("Image", image);
    localStorage.setItem("Email", email);
    localStorage.setItem("Company Name", companyName);
    localStorage.setItem("Company Number", companyNumber);
    localStorage.setItem("Unique Number", uniqueNumber);
    localStorage.setItem("Line of Business", lineofBusiness);
    localStorage.setItem("Company Revenue", companyRevenue);
    localStorage.setItem("Opening Time", openingTime);
    localStorage.setItem("Closing Time", closingTime);
    localStorage.setItem("Discount", discount);
    localStorage.setItem("Rating", rating);
    localStorage.setItem("Address1", address1);
    localStorage.setItem("Address2", address2);
    localStorage.setItem("Pincode", pincode);
    localStorage.setItem("Area", area);
    localStorage.setItem("City", city);
    localStorage.setItem("State", state);
    localStorage.setItem("Country", country);
  };

  const getData = () => {
    axios.get(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`).then((getData) => {
      setAPIData(getData.data);
    });
  };

  const onDelete = () => {
    axios
      .delete(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud/${idToDelete}`)
      .then(() => {
        navigate("/company/list");
        toggle();
      })
      .then(() => {
        getData();
      });
  };

  let navigate = useNavigate();

  const addUser = () => {
    navigate("/company/create");
  };

  const [open, setOpen] = useState(false);

  const toggle = () => setOpen(!open);

  const [search, setSearch] = useState("");

  return (
    <>
      <div className="container-fluid">
        <div className="row">
          <div className="col-lg-12" style={{ marginLeft: "-11px" }}>
            <SideMenu />
          </div>
        </div>
        <div className="row">
          <div className="col-lg-3"></div>
          <div className="col-lg-6">
            <Button primary style={{ width: "150px", height: "40px" }} onClick={addUser}>
              Add Company
            </Button>

            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by any Category"
              style={{
                position: "absolute",
                width: "260px",
                height: "40px",
                marginLeft: "285px",
                border: "none",
                fontSize: "15px",
                padding: "8px",
                borderRadius: "20px 20px 20px 20px",
              }}
            />
            <table style={{ width: "700px", height: "200px" }}>
              <thead style={{ margin: "50px" }}>
                <tr>
                  <th style={{ textAlign: "center" }}>List of Companies</th>
                </tr>
              </thead>
              {APIData.filter((data) =>
                Object.values(data).some((value) => value.toLowerCase().includes(search.toLowerCase()))
              ).map((data, id) => {
                return (
                  <>
                    <tbody key={id}>
                      <li
                        style={{
                          minHeight: "140px",
                          borderRadius: "5px",
                          margin: "20px 0px",
                          listStyle: "none",
                          padding: "25px",
                          backgroundColor: "white",
                          boxShadow: "0 0 20px 0px rgba(0,0,0,0.2)",
                        }}
                      >
                        <tr>
                          <Link to="/company/view">
                            <button
                              style={{
                                background: "transparent",
                                border: "none",
                                color: "blue",
                              }}
                              onClick={() => setData(data)}
                            >
                              {data.companyName}
                            </button>
                          </Link>
                        </tr>
                        <tr>{data.companyNumber}</tr>
                        <tr>{data.uniqueNumber}</tr>
                        <tr>{data.lineofBusiness}</tr>
                      </li>
                      <div
                        style={{
                          position: "absolute",
                          marginLeft: "580px",
                          marginTop: "-120px",
                        }}
                      >
                        <Dropdown
                          icon={
                            <AiIcons.AiOutlineEllipsis
                              style={{
                                color: "black",
                                fontSize: "1.3rem",
                                marginTop: "15px",
                                marginLeft: "30px",
                                border: "1px solid black",
                                width: "30px",
                                height: "30px",
                                borderRadius: "50%",
                              }}
                            />
                          }
                          pointing="top right"
                        >
                          <Dropdown.Menu>
                            <Dropdown.Item icon="edit" text="Edit">
                              <Link to="/company/edit">
                                <button
                                  onClick={() => setData(data)}
                                  style={{
                                    background: "transparent",
                                    border: "none",
                                  }}
                                >
                                  <FiIcons.FiEdit color="black" fontSize="1.3rem" /> Edit
                                </button>
                              </Link>
                            </Dropdown.Item>
                            <Dropdown.Item icon="delete" text="Delete">
                              <button
                                onClick={() => {
                                  setIdToDelete(data.id);
                                  toggle();
                                }}
                                style={{
                                  background: "transparent",
                                  border: "none",
                                }}
                                color="red"
                              >
                                <MdIcons.MdDelete color="black" fontSize="1.3rem" />
                                delete
                              </button>
                            </Dropdown.Item>
                          </Dropdown.Menu>
                        </Dropdown>
                      </div>
                    </tbody>
                  </>
                );
              })}
            </table>

            <Modal isOpen={open} toggle={toggle}>
              <ModalHeader toggle={toggle}>Warning</ModalHeader>
              <ModalBody>Are you sure to delete this id from the list...</ModalBody>
              <ModalFooter>
                <Button color="red" onClick={onDelete}>
                  Okay
                </Button>
                <Button color="primary" onClick={toggle}>
                  Cancel
                </Button>
              </ModalFooter>
            </Modal>
          </div>
        </div>
      </div>
    </>
  );
}

export default Read;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement