How To Fetch Data Using React Hooks

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:
  1. npx create-react-app reduxparttwo  
Open the newly created project in Visual Studio and install Bootstrap 
  1. npm install --save bootstrap    
Now, open the index.js file and add import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';  
Now, install the Axios library using the following command. Learn more about Axios here.
  1. npm install --save axios    
Now go to the src folder and add a new component, named 'Employeedata.js'. 
 
Add the following code in this component.
  1. import React, { useState, useEffect } from 'react'  
  2. import Axios from 'axios';  
  3. function Employeedata() {  
  4.     const [data, setData] = useState([]);  
  5.   
  6.     useEffect(() => {  
  7.         debugger;  
  8.         Axios  
  9.             .get("http://localhost:2345/Api/employee/DemoData")  
  10.             .then(result => setData(result.data));  
  11.         console.log(data);  
  12.         debugger;  
  13.     }, []);  
  14.     return (  
  15.         <div>  
  16.             <div className="row" style={{ 'margin'"10px" }}>  
  17.                 <div className="col-sm-12 btn btn-info">  
  18.                     How to fetch data Using React Hooks  
  19.                  </div>  
  20.             </div>  
  21.             <table class="table" >  
  22.                 <thead class="thead-dark">  
  23.                     <tr>  
  24.                         <th scope="col">Name</th>  
  25.                         <th scope="col">Age</th>  
  26.                         <th scope="col">Address</th>  
  27.                         <th scope="col">City</th>  
  28.                         <th scope="col">Salary</th>  
  29.                         <th scope="col">Department</th>  
  30.                     </tr>  
  31.                 </thead>  
  32.                 <tbody>  
  33.                     {data.map(item => {  
  34.                         return <tr key={item.Id}>  
  35.                             <td>{item.Name}</td>  
  36.                             <td>{item.Age}</td>  
  37.                             <td>{item.Address}</td>  
  38.                             <td>{item.City}</td>  
  39.                             <td>{item.Salary}</td>  
  40.                             <td>{item.Department}</td>  
  41.                         </tr>  
  42.                     })}  
  43.                 </tbody>  
  44.             </table>  
  45.   
  46.         </div>  
  47.     )  
  48. }  
  49.   
  50. export default Employeedata  
Add a reference of this component in the app.js file, and add the following code in the app.js file. 
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Employeedata from './Employeedata'  
  5. function App() {  
  6.   return (  
  7.     <div className="App">  
  8.    <Employeedata/>  
  9.     </div>  
  10.   );  
  11. }  
  12.   
  13. 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".
  1. CREATE TABLE [dbo].[DemoData](      
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,      
  3.     [Name] [nvarchar](50) NULL,      
  4.     [Age] [nvarchar](50) NULL,      
  5.     [Address] [nvarchar](50) NULL,      
  6.     [City] [nvarchar](50) NULL,      
  7.     [Salary] [nvarchar](50) NULL,      
  8.     [Department] [nvarchar](50) NULL,      
  9.  CONSTRAINT [PK_DemoData] PRIMARY KEY CLUSTERED       
  10. (      
  11.     [Id] ASC      
  12. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]      
  13. ON [PRIMARY]      
  14. 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.
  1. using Employeemanger.Models;    
Now add a method to fetch data from the database.  
  1. [Route("DemoData")]      
  2.         [HttpGet]      
  3.         public object DemoData()      
  4.         {      
  5.             return DB.DemoDatas.ToList();      
  6.         }   
Complete employee controller code:
  1. using System;      
  2. using System.Collections.Generic;      
  3. using System.Linq;      
  4. using System.Net;      
  5. using System.Net.Http;      
  6. using System.Web.Http;      
  7. using Employeemanger.Models;      
  8.       
  9.       
  10. namespace Employeemanger.Controllers      
  11. {      
  12.       
  13.     [RoutePrefix("api/employee")]      
  14.     public class EmployeeController : ApiController      
  15.     {      
  16.         ContactManagerEntities2 DB = new ContactManagerEntities2();      
  17.       
  18.         [Route("DemoData")]      
  19.         [HttpGet]      
  20.         public object DemoData()      
  21.         {      
  22.             return DB.DemoDatas.ToList();      
  23.         }      
  24.       
  25.               
  26. }      
  27. }   
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:
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");                  
  2. config.EnableCors(cors);     
Now, go to Visual Studio code and run the project by using the following command: 'npm start'.
 
 

Summary

 
In this article, we learned how to fetch data using web API and React Hooks.