The main objectives of this article are:
(Step:2)(Step 3)
In the next article, we will implement the Delete operation.
- Create Get By Id Endpoint In API Project.
- Creating Update Endpoint In API Project.
- Creating A React Component To Show Update Form
Create Get By Id Endpoint In API Project:
To update any record, we first need to fetch it by its 'id'. So let's create a get id by an endpoint in our API project.
API_Project/Controllers/SuperVillainController.cs:
[HttpGet] [Route("{id:int}")] public async Task<IActionResult> Get(int id) { var villainById = await _reactJSDemoContext .SuperVillain.Where(_ => _.Id == id) .FirstOrDefaultAsync(); return Ok(villainById); }
- (Line: 2)Since it is a second HTTP Get Action method, so we have to explicitly specify the route.
- The route expression '{id:int}' represent 'id' value must be integer value.
- (Line: 5-7) Fetching the record by 'id' from the database.
Create Update Endpoint In API Project:
Let's create the HTTP PUT action method.
API_Project/Controllers/SuperVillainController.cs:
[HttpPut] public async Task<IActionResult> Put(SuperVillain villainToUpdate) { _reactJSDemoContext.SuperVillain.Update(villainToUpdate); await _reactJSDemoContext.SaveChangesAsync(); return Ok(villainToUpdate); }
- (Line: 1) The 'HttpPut' verb makes our action method can be accessed by the HTTP PUT request.
- (Line: 2) Here to the action method we are passing our record that needs to be updated. In this payload, the 'id' value should be mandatory.
- (Line: 4) Using the 'Update' method attach our payload data to the database context.
- (Line: 5) Using the 'SaveChangesAsync()' method save our changes to the database.
Create A 'UpdateSuperVillain' Component In React App:
Let's create a new react component like 'UpdateSuperVillian' to handle the update form.
React_App/src/pages/UpdateSupervillian.js:
function UpdateSuperVillain() { return ( <></> ); } export default UpdateSuperVillain;
Configure 'UpdateSuperVillain' Route In App Component:
Let's add routing for the 'UpdateSuperVillain' component in the 'App' component.
React_App/src/App.js:
import UpdateSuperVillain from "./pages/UpdateSuperVillain"; // existing code hidden for display purpose function App() { return ( <Layout> <Routes> <Route path="/supervillain-update/:id" element={<UpdateSuperVillain />} /> </Routes> </Layout> ); } export default App;
- Here the route ':id' represents the placeholder for a dynamic 'id' value in the route.
Implement Update Form Logic:
Let's implemented the update form logic in the 'UpdateSuperVillain' component.
React_App/src/pages/UpdateSuperVillain.js:
import { useRef, useEffect } from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import axios from "axios"; import { useNavigate, useParams } from "react-router-dom"; function UpdateSuperVillain() { const superVillainName = useRef(""); const franchise = useRef(""); const powers = useRef(""); const imgUrl = useRef(""); const navigate = useNavigate(); const { id } = useParams(); useEffect(() => { axios.get(`https://localhost:7273/SuperVillain/${id}`).then((response) => { superVillainName.current.value = response.data.villainName; franchise.current.value = response.data.franchise; powers.current.value = response.data.powers; imgUrl.current.value = response.data.imageUrl; }); }, []); function updateVillainHandler() { var payload = { villainName: superVillainName.current.value, powers: powers.current.value, franchise: franchise.current.value, imageUrl: imgUrl.current.value, id: id, }; axios .put(`https://localhost:7273/SuperVillain/`, payload) .then((response) => { navigate("/"); }); } return ( <> <legend>Update SuperVilian</legend> <form> <Form.Group className="mb-3" controlId="formSuperVillainName"> <Form.Label>Super Villain Name</Form.Label> <Form.Control type="text" ref={superVillainName} /> </Form.Group> <Form.Group className="mb-3" controlId="formFranchise"> <Form.Label>Franchise</Form.Label> <Form.Control type="text" ref={franchise} /> </Form.Group> <Form.Group className="mb-3" controlId="formPowers"> <Form.Label>Powers</Form.Label> <Form.Control as="textarea" rows={3} ref={powers} /> </Form.Group> <Form.Group className="mb-3" controlId="formImgUrl"> <Form.Label>Image URL</Form.Label> <Form.Control type="text" ref={imgUrl} /> </Form.Group> </form> <Button variant="primary" type="button" onClick={updateVillainHandler}> Submit </Button> </> ); } export default UpdateSuperVillain;
- (Line: 8-11) Declared the 'useRef' variables which we use to read the form data.
- (Line: 13) Declared 'navigate' variable of type 'useNavigate()'.
- (Line: 15) The 'useParams()' loads from the 'react-router-dom' helps to read the dynamic data from the route.
- (Line: 17-24) Fetching the record to edit based on the 'id' value. To execute this API call only once we pass an empty array as the second parameter to the 'useEffect()'.
- (Line: 26-39) Invoking the HTTP put API call for updating the record.
- (Line: 62) The button click event registered with the 'updateVillainHandler' method.
'Edit' Button:
Let's add the 'Edit' button on to the 'AllSuperVillain' component.
React_App/src/pages/AllSuperVillain.js:
// existing code hidden for display purpose function AllSuperVillain() { return ( <> <Row md={3} className="g-4 mt-1"> {superVillains.map((sv) => { return ( <Col key={sv.id}> <Card> <Card.Text> <b>Powers: </b> {sv.powers} </Card.Text> <Button variant="primary" onClick={() => navigate(`/supervillain-update/${sv.id}`)} > Edit </Button> </Card.Body> </Card> </Col> ); })} </Row> </> ); } export default AllSuperVillain;
- Here we can see the 'Edit' button click is registered with an arrow function that contains logic to navigate to the 'UpdateSuperVaillain' component
(Step:2)(Step 3)
In the next article, we will implement the Delete operation.
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-5 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-7 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Part-7 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Comments
Post a Comment