The main objectives of this article are:
- Create an API endpoint to fetch all records
- Create ReactJS component to display all records
Create 'SuperVillain' Controller In API Project:
A Controller is an entity or class that contains logical methods or function that gets executed for an HTTP request from the clients.
Let's create a controller 'SuperVillianController.cs'.
API_Project/Controllers/SuperVillianController.cs:
using Microsoft.AspNetCore.Mvc; using ReactDemo.API.Data; namespace ReactDemo.API.Controllers; [ApiController] [Route("[controller]")] public class SuperVillainController : ControllerBase { private readonly ReactJSDemoContext _reactJSDemoContext; public SuperVillainController(ReactJSDemoContext reactJSDemoContext) { _reactJSDemoContext = reactJSDemoContext; } }
- (Line: 6) The 'ApiController' attribute applies all API rules to the controller.
- (Line: 7) The 'Route("[controller]")' attribute enables the attribute routing for controller. The '[controller]' expression represents the name of the controller that will be part of the URL.
- (Line: 8) To make our 'SuperVillainController' class an API controller it should inherit the 'Controller Base'.
- (Line: 10-14) Injected our database context into our controller constructor.
Create Get Endpoint Action Method In API Project:
In an API action method, the logic unit gets executed for the HTTP request and also serves the response to the users.
Let's create an action method to implement the read operation(fetching data).
API_Project/Controllers/SuperVillainController.cs:
using Microsoft.EntityFrameworkCore; [HttpGet] public async Task<IActionResult> Get() { var villains = await _reactJSDemoContext.SuperVillain.ToListAsync(); return Ok(villains); }
- (Line: 3) The 'HttpGet' attribute enables our action method needs to be invoked only for HTTP request
- (Line: 6) The 'ToListAsync()' method fetches all records from the database asynchronously.
- (Line: 7) The 'Ok()' method return the success response.
Create A 'AllSuperVillain' React Component In React Application:
Let's create a react component like 'AllSuperVillain.js' inside of a new folder called 'pages'.
React_App/src/pages/AllSuperVillain.js:
function AllSuperVillain() { return <></>; } export default AllSuperVillain;
Install Axios Library In To React Application:
To invoke the HTTP API calls one of the best-recommended third-party libraries is Axios.
npm i axios
Consume API From 'AllSuperVillain' React Component:
Let's try to consume the API and then render the response 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"; function AllSuperVillain() { const [superVillains, setSuperVillains] = useState([]); useEffect(() => { axios.get("https://localhost:7273/SuperVillain").then((response) => { setSuperVillains((data) => { return response.data; }); }); }, []); return ( <> <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> </Card.Body> </Card> </Col> ); })} </Row> </> ); } export default AllSuperVillain;
- The 'useState' loads from the 'react' library. In react js application to maintain a state of data we will use the 'useState'. If the value of 'useState' variable changes entire component gets refreshed. The default value can be given while it is initialized. The 'useState' return array of 2 values, where the first value will be the data and the second value will be the function to update the state.
- The 'useEffect' loads from the 'react' library. The 'useEffect(()=> {},[])' contains 2 in parameters where first parameter is arrow function in which we can write logic to executes and second parameter is array to which we can pass 'useState' values. So whenever the second parameter value changes then only the 'useEffect' gets executed. If the second parameter array is empty then the 'useEffect' get executes only once.
- (Line: 8) Declared the 'useState' where its value will be accessed through 'superVillians' and to update it we have to use the 'setSuperVillains' function.
- (Line: 10-16) Here used the 'useEffect' where we implemented our Axios API call logic. So to execute the logic inside of 'useEffect' only once we passed the second parameter as an empty array.
- (Line: 20) Used react js bootstrap 'Row' component and specified its property like 'md={3}' only render 3 columns from medium size screens.
- (Line: 21) The 'superVillians' state variable which contains API response is looping to render the data.
- (Line: 23) The 'Col' component specified the 'key' property which is recommended to provide unique value for looping items.
- (Line: 23-33) In react js to render dynamic data we have to using single flower brace '{}'
React_App/src/App.js:
import logo from './logo.svg'; import './App.css'; import Layout from './components/shared/Layout'; import AllSuperVillain from './pages/AllSuperVillain'; function App() { return ( <Layout> <AllSuperVillain></AllSuperVillain> </Layout> ); } export default App;
- Here are 'AllSuperVillain' component element renders inside of the 'Layout' component element
Enable Cors Service In API Project:
In our API application, we have to allow our ReactJS domain to consume the API. For that, we have to enable the Cors policy.
In the 'Program.cs' file let's register the 'CORS' service as below.
API_Project/Progrm.cs:
- Here we added 'CORS' policy to give access to our react js application to consume the API.
Now check our React Js application and we can observe API is able to consume by our react app.
In the next article, we are going to implement the create 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-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-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-7 | .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-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-7 | .NET 6 Web API | SQL Database | React JS(v18) | CRUD Example
Comments
Post a Comment