Blog>
Snippets

Delete a Record with Confirmation Modal

Use the useMutation hook to delete a record, such as a blog post, from the database after the user confirms the action through a modal dialog.
import React, { useState } from 'react';
import { useMutation } from 'react-query';
import axios from 'axios';
import Modal from './Modal'; // Assume Modal is a component for displaying modals
Imports React, useState hook for handling modal visibility, useMutation hook from react-query for deletion logic, axios for making HTTP requests, and a Modal component for confirmation.
const DeletePostButton = ({ postId }) => {
    const [showModal, setShowModal] = useState(false);
    const mutation = useMutation(() => axios.delete(`https://jsonplaceholder.typicode.com/posts/${postId}`), {
        onSuccess: () => alert('Post deleted successfully'),
    });

    const handleDelete = () => {
        setShowModal(true);
    };

    const confirmDelete = () => {
        mutation.mutate();
        setShowModal(false);
    };

    return (
        <div>
            <button onClick={handleDelete}>Delete Post</button>
            {showModal && <Modal onConfirm={confirmDelete} onClose={() => setShowModal(false)} />}
        </div>
    );
};

export default DeletePostButton;
Defines a DeletePostButton component, which renders a button for deleting a post. When clicked, a modal dialog is shown asking for confirmation. Uses the useMutation hook to send a DELETE request when confirmed. The onSuccess option is used to display an alert upon successful deletion.