Introduction
In this article, we will learn how to fetch data using a web API and React Hooks. Hooks are a new concept introduced in React 16.8. They are an alternative to classes.
Prerequisites
- Basic knowledge of React.js and Web API.
- Visual Studio and Visual Studio Code IDE should be installed on your system.
- SQL Server Management Studio
- Basic knowledge of Bootstrap and HTML
Create ReactJS project
First, let's create a React application with the following command:
- npx create-react-app reduxparttwo
Open the newly created project in Visual Studio and install Bootstrap
- npm install --save bootstrap
Now, open the index.js file and add import Bootstrap.
- import 'bootstrap/dist/css/bootstrap.min.css';
Now, install the Axios library using the following command. Learn more about
Axios here.
Now go to the src folder and add a new component, named 'Employeedata.js'.
Add the following code in this component.
- import React, { useState, useEffect } from 'react'
- import Axios from 'axios';
- function Employeedata() {
- const [data, setData] = useState([]);
-
- useEffect(() => {
- debugger;
- Axios
- .get("http://localhost:2345/Api/employee/DemoData")
- .then(result => setData(result.data));
- console.log(data);
- debugger;
- }, []);
- return (
- <div>
- <div className="row" style={{ 'margin': "10px" }}>
- <div className="col-sm-12 btn btn-info">
- How to fetch data Using React Hooks
- </div>
- </div>
- <table class="table" >
- <thead class="thead-dark">
- <tr>
- <th scope="col">Name</th>
- <th scope="col">Age</th>
- <th scope="col">Address</th>
- <th scope="col">City</th>
- <th scope="col">Salary</th>
- <th scope="col">Department</th>
- </tr>
- </thead>
- <tbody>
- {data.map(item => {
- return <tr key={item.Id}>
- <td>{item.Name}</td>
- <td>{item.Age}</td>
- <td>{item.Address}</td>
- <td>{item.City}</td>
- <td>{item.Salary}</td>
- <td>{item.Department}</td>
- </tr>
- })}
- </tbody>
- </table>
-
- </div>
- )
- }
-
- export default Employeedata
Add a reference of this component in the app.js file, and add the following code in the app.js file.
- import React from 'react';
- import logo from './logo.svg';
- import './App.css';
- import Employeedata from './Employeedata'
- function App() {
- return (
- <div className="App">
- <Employeedata/>
- </div>
- );
- }
-
- export default App;
Create a Database and a Table
Open SQL Server Management Studio and create a database named "contactmanager". In this database, create a table. Give that table a name like "demodata".
- CREATE TABLE [dbo].[DemoData](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Age] [nvarchar](50) NULL,
- [Address] [nvarchar](50) NULL,
- [City] [nvarchar](50) NULL,
- [Salary] [nvarchar](50) NULL,
- [Department] [nvarchar](50) NULL,
- CONSTRAINT [PK_DemoData] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
Now add a demo data in this table.
Create a new Web API project
Open Visual Studio and create a new project.
Change the name to Employeemanager.
Choose the template as Web API.
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Click on the "ADO.NET Entity Data Model" option and click "Add".
Select EF Designer from the database and click the "Next" button.
Add the connection properties and select database name on the next page and click OK.
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK.
Now our data model is successfully created.
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace in the Employee controller.
- using Employeemanger.Models;
Now add a method to fetch data from the database.
- [Route("DemoData")]
- [HttpGet]
- public object DemoData()
- {
- return DB.DemoDatas.ToList();
- }
Complete employee controller code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using Employeemanger.Models;
-
-
- namespace Employeemanger.Controllers
- {
-
- [RoutePrefix("api/employee")]
- public class EmployeeController : ApiController
- {
- ContactManagerEntities2 DB = new ContactManagerEntities2();
-
- [Route("DemoData")]
- [HttpGet]
- public object DemoData()
- {
- return DB.DemoDatas.ToList();
- }
-
-
- }
- }
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines:
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Now, go to Visual Studio code and run the project by using the following command: 'npm start'.
In this article, we learned how to fetch data using web API and React Hooks.