The main objectives of this article are:
(step 2)(step 3)
In the next article, we will implement the update operation.
- Create HTTP Post endpoint in API Project.
- Create React JS component with a form to add a new item
Create Post Endpoint Action Method In API Project:
Let's create an HTTP Post action method to save a new record into the database.
API_Project/Controllers/SuperVillainController.cs:
[HttpPost] public async Task<IActionResult> Post(SuperVillain newSuperVillain) { _reactJSDemoContext.SuperVillain.Add(newSuperVillain); await _reactJSDemoContext.SaveChangesAsync(); return Ok(newSuperVillain); }
- (Line: 1) The 'HttpPost' attribute makes our action method invoke only for HTTP Post requests.
- (Line: 2) Here our action method should receive the item to add as a payload input parameter.
- (Line: 4) Our new record data instance adding to the database context.
- (Line: 5) The 'SaveChangesAsync()' method inserts the new record into the database.
Create 'AddSuperVillain' Component In React App:
On the 'pages' folder let's create a new react js component like 'AddSuperVillain'.
React_App/src/pages/AddSuperVillain.js:
function AddSuperVillain() { return <></>; } export default AddSuperVillain;
Install React Router Package:
We add a 2nd-page component in our application which means page components need to be loaded as per their navigation. So to implement navigation we need to install the React Router library
npm i react-router-dom
Create Form To Consume HTTP Post API Call In React App:
Let's create a form to add the new item with the help of the HTTP Post API call.
React_App/src/pages/AddSuperVillain.js:
import { useRef } from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import axios from "axios"; import { useNavigate } from "react-router-dom"; function AddSuperVillain() { const superVillainName = useRef(""); const franchise = useRef(""); const powers = useRef(""); const imgUrl = useRef(""); const navigate = useNavigate(); function addVillainHandler() { var payload = { villainName: superVillainName.current.value, powers: powers.current.value, franchise: franchise.current.value, imageUrl: imgUrl.current.value, }; axios .post("https://localhost:7273/SuperVillain", payload) .then((response) => { navigate("/"); }); } return ( <> <legend>Add A New SuperVilian Character</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={addVillainHandler}> Submit </Button> </> ); } export default AddSuperVillain;
- The 'useRef()' loads from the 'react' library. This variable of type 'useRef' can be mapped with the 'ref' attribute of an HTML tag so that we can access the element values with it. So it is very useful for reading the form data.
- (Line: 8-11) Here constant variable is initialized with 'useRef', so all these variables will be mapped with form fields to read the field values.
- (Line: 15-28) The 'addVillainHandler' is a function that holds logic to post the form data to the HTTP Post API call.
- (Line: 16-21) API payload object and here we can observe that to read the form filed value we are using eg:'superVillainName.current.value' that means we accessing reference of the HTML element to read its value.
- (23-27) Axios post call invocation, on success navigating back to the home page('AllSuperVillains.js component is our home page and routing will be configured in upcoming steps')
- (34-49) Each form field is mapped to the 'ref' attribute to get access of fields
- (51-53) Form submit it click event can be raised using 'onClick'. Here we need to register the 'addVillainHandler' to the 'onClick' event.
'Add' Button In 'AllSuperVillain' Component:
So from our home page('AllSuperVillain') component to navigating to the 'AddSuperVillian' component, we have to add the 'Add' button in the 'AllSuperVillain' component.
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"; // existing code hidden for display purpose function AllSuperVillain() { const navigate = useNavigate(); return ( <> <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 ( <!-- --> ); })} </Row> </> ); } export default AllSuperVillain;
- (Line: 10) Initialized the 'useNavigate()' that loads from the 'react-router-dom' library.
- (Line: 16-22) The 'Add A Villan' button renders and click event navigates to the route '/supervillain-create'(routes configuration explained in next step) that loads the 'AddSuppervillain' component.
Configure The Component Routing Navigation:
Let's configure the navigation for the Reactjs application in 'App.js'
React_App/src/App.js:
import './App.css'; import Layout from './components/shared/Layout'; import AllSuperVillain from './pages/AllSuperVillain'; import AddSuperVillain from './pages/AddSuperVillain'; import { Route, Routes } from "react-router-dom"; function App() { return ( <Layout> <Routes> <Route path="/" element={<AllSuperVillain />} /> </Routes> <Routes> <Route path="/supervillain-create" element={<AddSuperVillain />} /> </Routes> </Layout> ); } export default App;
- Here we can observe our page components configured with routes
Now in 'index.js' the 'App' component element must be encapsulated with the 'BrowserRouter' element.
React_App/src/index.js:
Let's test the create operation by creating a new item.import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import { BrowserRouter } from "react-router-dom"; import "bootstrap/dist/css/bootstrap.min.css"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <BrowserRouter> <App /> </BrowserRouter> );
(step 1)
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-4 | .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-7 | .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-7 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
my post ,method not working. when i click submit button nothing happens. when i open console, it shows more 50 errors, all errors about axios post method with error code 500. please guide me. i searched about it but didn't find anything helpful.
ReplyDelete