Home > Back-end >  How can I return back to the page after I click yes in a modal?
How can I return back to the page after I click yes in a modal?

Time:02-22

I have just implemented the modal, when the user deletes a client, the client is deleted. But the problem is that when I click yes in modal to delete the client, the modal is still open and it won't close.

ClientList.js

export default function ListClients() {
 const [showModal, setShowModal] = useState();
 const [userlist, setUserlist] = useState([]);

   function deleteClient() {
       const userParams = {
          clientName:
        clientName,
          country: country,
          clientid: selectedID,
        };
        
       axios
          .delete(process.env   "client", {
        data: clientParams,
          })
          .then((response) => {
        setClientlist(clientlist.filter((client) => client.id !== clientId));
          })
          .catch((error) => {
        console.log(error);
          });

  // const openModal = () => { 
  //   setShowModal(prev => !prev);
  // };


  }

return(
     <div>
    <tbody>
        {userlist.length > 0 ? (
           userlist.map((userlist) => (
             <tr key={userlist.id}>
                <td>
                  <div">
                      {userlist.id}
                   </div>
                </td>
                <td>
                  <button type="button" onClick={() => {setSelectedID(clientlist.id); setShowModal(true)}}> 
                      Delete
                  </button>
                 </td
             </tr>
        </tbody>

         //the idea is to pass the  state for modal to show 
       <ModalDelete showModal={showModal} setShowModal={setShowModal} onDel={deleteClient(clientlist.id)}/>
      </div>
);

ModalDelete.js

export default function ModalDelete({ showModal, setShowModal,onDel }) {
 
return(
  <div>
    { showModal ? <Transition.Root show={showModal}>  
       <div>
       <p> Are you sure you want to delete the client?</p>
    </div>

    <div>
        <button type="button" onClick={onDel}>Yes</button>

        <button type="button" onClick={() => {setShowModal(false);}} >
            Go Back
         </button>

          </div>
    </Transition.Root> : null }
  </div>
);
}

How can I not show the modal after the user clicks yes to delete the client?

CodePudding user response:

Calling setShowModal(false) after onDel:

<button type="button" onClick={() => {
   onDel();
   setShowModal(false);
}}>Yes</button>

And rewrite ModalDelete in this way:

<ModalDelete showModal={showModal} setShowModal={setShowModal} onDel={() => deleteClient(clientlist.id)}/>
  • Related