My modal always closes when I delete a url that comes from the backend, apparently it could be a useState issue or maybe the async function. I’ll describe what I want to do:
I want to delete a URL and the delete button opens a modal, calm, everything is right.
When I confirm the deletion, I want a modal to appear with a loading screen and after the URL is deleted, it appears that the URL has been successfully deleted.
But after deleting the URL, a loading frame appears and the modal closes… Please, whoever knows how to solve it, tell me, I would appreciate it very much!
When I remove the delete URL function and leave only a delay of 2 seconds, the modal works normally. Besides that I didn’t get any more information…
Francisco Ylano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The procedure of closing automatically because of the state update or the async function completing. So you need to prevent the modal from closing prematurely and implement the loading and success states you want.
import React, { useState } from 'react';
const DeleteModal = ({ url, onDelete }) => {
const [isOpen, setIsOpen] = useState(true); // Keep modal open
const [loading, setLoading] = useState(false); // Loading state
const [success, setSuccess] = useState(false); // Success state
const handleDelete = async () => {
setLoading(true); // Start loading
try {
await onDelete(url);
setSuccess(true); // Mark as success after deletion
} catch (error) {
console.error('Error deleting URL:', error);
// Optionally handle error and show message
} finally {
setLoading(false); // Stop loading, whether success or error
}
};
return (
<div className={`modal ${isOpen ? 'open' : ''}`}>
{/* Modal content */}
{!loading && !success && (
<>
<h2>Are you sure you want to delete this URL?</h2>
<button onClick={handleDelete}>Confirm Delete</button>
</>
)}
{loading && (
<div>
<h2>Deleting URL...</h2>
{/* Add your loading spinner here */}
</div>
)}
{success && (
<div>
<h2>URL successfully deleted!</h2>
<button onClick={() => setIsOpen(false)}>Close</button>
</div>
)}
</div>
);
};
export default DeleteModal;