The main objectives of this article are:
- Create HTTP delete endpoint in API Project.
- React application to invoke the delete API.
Create HTTP Delete Endpoint In API Project:
Let's create an HTTP delete endpoint in the API project.
API_Project/Controllers/SuperVillainController.cs:
[HttpDelete] [Route("{id:int}")] public async Task<IActionResult> Delete(int id) { var villainToDelete = await _reactJSDemoContext.SuperVillain.FindAsync(id); if (villainToDelete == null) { return NotFound(); } _reactJSDemoContext.SuperVillain.Remove(villainToDelete); await _reactJSDemoContext.SaveChangesAsync(); return Ok(); }
- (Line: 1) The 'HttpDelete' attribute allows us action method can be consumed for only HTTP delete requests.
- (Line: 2) The 'Route' attribute defined where we need to pass the integer 'id' value.
- (Line: 5) Based on the 'id' value trying to fetch the record from the database.
- (Line: 6-9) Checking whether a record exists in the database or not.
- (Line: 10) Using the 'Remove()' method we pass our record to be deleted from the database.
- (Line: 12) The 'SaveChangesAsync()' deletes the record from the database.
Create A Shared React Component Like 'DeleteConfirmation':
Let's create a shared 'DeleteConfirmation' react component in the 'shared/components' folder.
React_App/shared/components/DeleteConfirmation.js:
import Button from "react-bootstrap/Button"; import Modal from "react-bootstrap/Modal"; function DeleteConfirmation(props) { return ( <> <Modal show={props.showModal} onHide={() => { props.hideConfirmDeleteHandler(); }} keyboard={false} > <Modal.Header closeButton> <Modal.Title>{props.title}</Modal.Title> </Modal.Header> <Modal.Body>{props.body}</Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={() => { props.hideConfirmDeleteHandler(); }} > Close </Button> <Button variant="danger" onClick={() => { props.confirmDeleteHandler(); }} > Confirm Delete </Button> </Modal.Footer> </Modal> </> ); } export default DeleteConfirmation;
- Here are 'DeleteConfirmation' component contains react-bootstrap modal code. So this 'DeleteConfiramtion' is a shared component that can be used anywhere in our application.
- (Line: 8) The 'show' is the boolean property of the 'Modal' component. The parent component passes its value through 'props.showModal'(here showModal is our custom property name which must be passed by the parent component and its value should be boolean). So if 'show' property receives 'true' then opens up the modal.
- (Line: 9-10) The 'onHide' get triggered by the 'x'(close button) on the right-top corner of the modal. Here 'onHide' register with arrow function which internally calls a method of parent component like 'props.hideConfirmDeleteHandler'.
- (Line: 15) Dynamic 'props.title' property for the modal title.
- (Line: 17) Dynamic 'props.body' property for the modal body.
- (Line: 19-26) Close button, click event register with arrow function which internally calls a method parent component like 'props.hideConfirmDeleteHandler'.
- (Line: 27-34) Confirm Delete button, click event register with arrow function which internally calls a method of parent component like 'props.ConfirmDeleteHandler'.
Invoke The 'DeleteConfirmation' Component From The 'AllSuperVillain' Component:
Let's add the 'DeleteConfirmation' component element tag into our 'AllSuperVillian'. So whenever the user click's delete button our confirmation modal should show.
React_App/src/pages/AllSuperVillain.js:
import { Row } from "react-bootstrap"; import Card from "react-bootstrap/Card"; import Col from "react-bootstrap/Col"; import { useEffect, useState } from "react"; import axios from "axios"; import { useNavigate } from "react-router-dom"; import Button from "react-bootstrap/Button"; import DeleteConfirmation from "../components/shared/DeleteConfimation"; function AllSuperVillain() { const [superVillains, setSuperVillains] = useState([]); const navigate = useNavigate(); const [showModal, setShowModal] = useState(false); const [itemToDeleteId, setItemToDeleteId] = useState(0); useEffect(() => { axios.get("https://localhost:7273/SuperVillain").then((response) => { setSuperVillains((data) => { return response.data; }); }); }, []); function confirmDeleteHandler() { axios .delete(`https://localhost:7273/SuperVillain/${itemToDeleteId}`) .then((response) => { setShowModal(false); setSuperVillains((existingData) => { return existingData.filter((_) => _.id !== itemToDeleteId); }); setItemToDeleteId(0); }); } function showConfirmDeleteHandler(id) { setShowModal(true); setItemToDeleteId(id); } function hideConfirmDeleteHandler() { setShowModal(false); setItemToDeleteId(0); } return ( <> <DeleteConfirmation showModal={showModal} title="Delete Confirmation" body="Are you want delete this itme?" confirmDeleteHandler={confirmDeleteHandler} hideConfirmDeleteHandler={hideConfirmDeleteHandler} ></DeleteConfirmation> <Row className="mt-2"> <Col md={{ span: 4, offset: 4 }}> <Button variant="primary" type="button" onClick={() => navigate("/supervillain-create")} > Add A Villain </Button> </Col> </Row> <Row md={3} className="g-4 mt-1"> {superVillains.map((sv) => { return ( <Col key={sv.id}> <Card> <Card.Img variant="top" src={sv.imageUrl} /> <Card.Body> <Card.Title>{sv.villainName}</Card.Title> <Card.Text> <b>Franchis:</b> {sv.franchise} </Card.Text> <Card.Text> <b>Powers: </b> {sv.powers} </Card.Text> <Button variant="primary" onClick={() => navigate(`/supervillain-update/${sv.id}`)} > Edit </Button> <Button type="button" variant="danger" onClick={() => showConfirmDeleteHandler(sv.id)} > Delete </Button> </Card.Body> </Card> </Col> ); })} </Row> </> ); } export default AllSuperVillain;
- (Line: 14) The 'showModal' & 'setShowModal' are useState variables used to show and hide the modal.
- (Line: 15) The 'itemToDeleteId' & 'setItemToDeleteid' are useState variables used to maintain id of the record that need to be deleted.
- (Line: 25-35) The function 'confirmDeleteHandler' contains logic to invoke the delete API call.
- After deleting API success we are updating a few 'useState'. The 'setShowModal' is assigned to false to close the modal. The 'setSuperVillains' update to remove the deleted from it. The 'setItemToDeleteId' value assigned to '0'.
- (Line: 37-40) The function 'showConfirmDeleteHandler' will invoke by the delete button. It contains logic like 'setShowModal' to true which opens the delete confirmation modal and 'setItemToDeleteId' value contains the record item to be deleted.
- (Line: 42-46) The function 'hideConfirmationDeleteHandler' will invoke by the 'cancel' button on modal. It contains logic like 'setShowModal' to true which closes the modal and 'setItemToDelteId' reset to value '0'.
- (Line: 50-56) Rendered the 'DeleteConfirmation' component with dynamic input properties like 'showModal', 'title', 'body', 'confirmDeleteHandler', 'hideConfirmDeleteHandler'.
- (Line: 89-95) The 'Delete' button clicks the event registered with the arrow function. The logic inside of the arrow function is to invoke the 'showConfirmDelteHandler' by inputting the 'id' of the item to delete.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on the .NET 6 Web API and React JS(v18). using I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-1 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-2 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-3 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-4 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-5 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-6 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-2 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-3 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-4 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-5 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-6 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Thank you!
ReplyDelete