CRUD Operations In ReactJS With Hooks

Introduction 

 
In this article we will explain about React hooks and how to implement hooks in  React. Hooks are a new concept that were  introduced in React 16.8. Hooks are an alternative to classes. In this article I'm going to create CRUD operations using React hook and web api.
 
You can check my previous article in which we use class components to perfrom CRUD from the below mentioned link,
Prerequisites
  • We should have the 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 React strap and HTML
Implementation Steps
  • Create React App
  • Install Bootstrap and React strap
  • Install Axios
  • Add React Router
  • React Hooks and Get, Post data using Axios
  • Create a Database and Table
  • Create Asp.net Web API Project

Create ReactJS Project

 
Let's create a React app by using this following command.
  1. npx create-react-app crudhooks  
Open the newly created project in Visual Studio Code and install Reactstrap and Bootstrap in this project by using the following commands respectively. Learn more about  Reactstrap.
  1. npm install --save bootstrap    
  2. npm install --save reactstrap react react-dom   
Now, open the index.js file and add import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';   
Now Install the Axios library by using the following command. Learn more about Axios
  1. npm install --save axios    
Now go to src folder and create a new folder and inside this folder add 3 new components,
  • Createemployee.js
  • Editemployee.js
  • EmployeList.js

Add Routing in ReactJS

 
Install react-router-dom package by using the following command
  1. npm install react-router-dom --save  
Open app.js file and imports of Router and Route (react-router-dom) and 3 components
  1. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
  2. import Createemployee from './CrudComponent/Createemployee'  
  3. import EmployeList from './CrudComponent/EmployeList'  
  4. import Editemployee from "./CrudComponent/Editemployee";  
Add the following code in app.js file
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
  5. import Createemployee from './CrudComponent/Createemployee'  
  6. import EmployeList from './CrudComponent/EmployeList'  
  7. import Editemployee from "./CrudComponent/Editemployee";  
  8. function App() {  
  9.   return (  
  10.     <div className="App">  
  11.      <Router>    
  12.       <div className="container">    
  13.         <nav className="btn btn-warning navbar navbar-expand-lg navheader">    
  14.           <div className="collapse navbar-collapse" >    
  15.            
  16.             <ul className="navbar-nav mr-auto">    
  17.               <li className="nav-item">    
  18.                 <Link to={'/Createemployee'} className="nav-link">Add Employee</Link>    
  19.               </li>    
  20.               <li className="nav-item">    
  21.                 <Link to={'/EmployeList'} className="nav-link">Employee List</Link>    
  22.               </li>    
  23.             </ul>    
  24.           </div>    
  25.         </nav> <br />    
  26.         <Switch>    
  27.           <Route exact path='/Createemployee' component={Createemployee} />    
  28.           <Route path='/edit/:id' component={Editemployee} />    
  29.           <Route path='/EmployeList' component={EmployeList} />    
  30.         </Switch>    
  31.       </div>    
  32.     </Router>    
  33.     </div>  
  34.   );  
  35. }  
  36. export default App;  
Now, open the Createemployee.js file and add the following code.
  1. import React, { useState, useEffect } from 'react'  
  2. import axios from 'axios';  
  3. import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
  4. function Createemployee(props) {  
  5.   const [employee, setemployee] = useState({ Name: '', Department: '', Age: '', City: '', Country: '', Gender: '' });  
  6.   const [showLoading, setShowLoading] = useState(false);  
  7.   const apiUrl = "http://localhost:62168/api/Hooks/CreateEmp";  
  8.   
  9.   const Insertemployee = (e) => {  
  10.     e.preventDefault();  
  11.     debugger;  
  12.     const data = { Name:employee.Name, Department: employee.Department, Age: employee.Age, City:employee.City, Country: employee.Country, Gender: employee.Gender };  
  13.     axios.post(apiUrl, data)  
  14.       .then((result) => {  
  15.         props.history.push('/EmployeList')  
  16.       });  
  17.   };  
  18.   const onChange = (e) => {  
  19.     e.persist();  
  20.     debugger;  
  21.     setemployee({...employee, [e.target.name]: e.target.value});  
  22.   }  
  23.   
  24.   return (  
  25.     <div className="app flex-row align-items-center">  
  26.       <Container>  
  27.         <Row className="justify-content-center">  
  28.           <Col md="12" lg="10" xl="8">  
  29.             <Card className="mx-4">  
  30.               <CardBody className="p-4">  
  31.                 <Form onSubmit={Insertemployee}>  
  32.                   <h1>Register</h1>  
  33.                   <InputGroup className="mb-3">  
  34.   
  35.                     <Input type="text" name="Name" id="Name" placeholder="Name" value={employee.Name} onChange={ onChange }  />  
  36.                   </InputGroup>  
  37.                    <InputGroup className="mb-3">  
  38.   
  39.                     <Input type="text" placeholder="Department" name="Department" id="Department" value={employee.Department} onChange={ onChange }/>  
  40.                   </InputGroup>  
  41.                   <InputGroup className="mb-3">  
  42.   
  43.                     <Input type="text" placeholder="Age" name="Age" id="Age"  value={employee.Age} onChange={ onChange }  />  
  44.                   </InputGroup>  
  45.                   <InputGroup className="mb-4">  
  46.   
  47.                     <Input type="text" placeholder="City" name="City" id="City" value={employee.City} onChange={ onChange }  />  
  48.                   </InputGroup>  
  49.                   <InputGroup className="mb-4">  
  50.   
  51.                     <Input type="text" placeholder="Country" name="Country" id="Country" value={employee.Country} onChange={ onChange } />  
  52.                   </InputGroup>  
  53.                   <InputGroup className="mb-4">   
  54.   
  55.                      <Input type="text" placeholder="Gender" name="Gender" id= "Gender" value={employee.Gender} onChange={ onChange } />  
  56.                   </InputGroup>   
  57.              <CardFooter className="p-4">  
  58.                 <Row>  
  59.                   <Col xs="12" sm="6">  
  60.                     <Button type="submit" className="btn btn-info mb-1" block><span>Save</span></Button>  
  61.                   </Col>  
  62.                   <Col xs="12" sm="6">  
  63.                     <Button className="btn btn-info mb-1" block><span>Cancel</span></Button>  
  64.                   </Col>  
  65.                 </Row>  
  66.               </CardFooter>  
  67.                 </Form>  
  68.               </CardBody>  
  69.             </Card>  
  70.           </Col>  
  71.         </Row>  
  72.       </Container>  
  73.     </div>  
  74.   )  
  75. }  
  76. export default Createemployee  
 Now, open the EmployeList.js file and add the following code.
  1. import React from 'react'  
  2. import { Badge, Card, CardBody, CardHeader, Col, Pagination, PaginationItem, PaginationLink, Row, Table } from 'reactstrap';  
  3. import axios from 'axios';  
  4. import { useState, useEffect } from 'react'  
  5. function EmployeList(props) {  
  6.   const [data, setData] = useState([]);  
  7.   
  8.   useEffect(() => {  
  9.     const GetData = async () => {  
  10.       const result = await axios('http://localhost:62168/api/hooks/employee');  
  11.       setData(result.data);  
  12.     };  
  13.   
  14.     GetData();  
  15.   }, []);  
  16.   const deleteeployee = (id) => {  
  17.     debugger;  
  18.     axios.delete('http://localhost:62168/api/hooks/Deleteemployee?id=' + id)  
  19.       .then((result) => {  
  20.         props.history.push('/EmployeList')  
  21.       });  
  22.   };  
  23.   const editemployee = (id) => {  
  24.     props.history.push({  
  25.       pathname: '/edit/' + id  
  26.     });  
  27.   };  
  28.   
  29.   return (  
  30.     <div className="animated fadeIn">  
  31.       <Row>  
  32.         <Col>  
  33.           <Card>  
  34.             <CardHeader>  
  35.               <i className="fa fa-align-justify"></i> Employee List  
  36.               </CardHeader>  
  37.             <CardBody>  
  38.               <Table hover bordered striped responsive size="sm">  
  39.                 <thead>  
  40.                   <tr>  
  41.                     <th>Name</th>  
  42.                     <th>Department</th>  
  43.                     <th>Age</th>  
  44.                     <th>City</th>  
  45.                     <th>Country</th>  
  46.                     <th>Gender</th>  
  47.                     <th>Action</th>  
  48.                   </tr>  
  49.                 </thead>  
  50.                 <tbody>  
  51.                   {  
  52.                     data.map((item, idx) => {  
  53.                       return <tr>  
  54.                         <td>{item.Name}</td>  
  55.                         <td>{item.Department}</td>  
  56.                         <td>{item.Age}</td>  
  57.                         <td>{item.City}</td>  
  58.                         <td>{item.Country}</td>  
  59.                         <td>  
  60.                           {item.Gender}  
  61.                         </td>  
  62.                         <td>  
  63.                           <div class="btn-group">  
  64.                             <button className="btn btn-warning" onClick={() => { editemployee(item.Id) }}>Edit</button>  
  65.                             <button className="btn btn-warning" onClick={() => { deleteeployee(item.Id) }}>Delete</button>  
  66.                           </div>  
  67.                         </td>  
  68.                       </tr>  
  69.                     })}  
  70.                 </tbody>  
  71.               </Table>  
  72.             </CardBody>  
  73.           </Card>  
  74.         </Col>  
  75.       </Row>  
  76.     </div>  
  77.   )  
  78. }  
  79.   
  80. export default EmployeList  
Now, open the Editemployee.js file and add the following code.
  1. import React, { useState, useEffect } from 'react'  
  2. import axios from 'axios';  
  3. import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
  4. function Editemployee(props) {  
  5.         const [employee, setemployee]= useState({Id:'',Name: '', Department: '', Age: '', City: '', Country: '', Gender: '' });  
  6.         const Url = "http://localhost:62168/api/Hooks/employeedetails?id=" + props.match.params.id;  
  7.         
  8.         useEffect(() => {  
  9.           const GetData = async () => {  
  10.             const result = await axios(Url);  
  11.             setemployee(result.data);  
  12.             
  13.           };  
  14.         
  15.           GetData();  
  16.         }, []);  
  17.         
  18.         const UpdateEmployee = (e) => {  
  19.           e.preventDefault();  
  20.           const data = {Id:props.match.params.id, Name:employee.Name, Department: employee.Department, Age: employee.Age, City:employee.City, Country: employee.Country, Gender: employee.Gender };  
  21.           axios.post('http://localhost:62168/api/Hooks/CreateEmp', data)  
  22.             .then((result) => {  
  23.               props.history.push('/EmployeList')  
  24.             });  
  25.         };  
  26.         
  27.         const onChange = (e) => {  
  28.           e.persist();  
  29.           setemployee({...employee, [e.target.name]: e.target.value});  
  30.         }  
  31.         
  32.         return (  
  33.                 <div className="app flex-row align-items-center">  
  34.                 <Container>  
  35.                   <Row className="justify-content-center">  
  36.                     <Col md="12" lg="10" xl="8">  
  37.                       <Card className="mx-4">  
  38.                         <CardBody className="p-4">  
  39.                           <Form onSubmit={UpdateEmployee}>  
  40.                             <h1>Update Employee</h1>  
  41.                         
  42.                             <InputGroup className="mb-3">  
  43.             
  44.                               <Input type="text" name="Name" id="Name" placeholder="Name" value={employee.Name} onChange={ onChange }  />  
  45.                             </InputGroup>  
  46.                              <InputGroup className="mb-3">  
  47.             
  48.                               <Input type="text" placeholder="Department" name="Department" id="Department" value={employee.Department} onChange={ onChange }/>  
  49.                             </InputGroup>  
  50.                             <InputGroup className="mb-3">  
  51.             
  52.                               <Input type="text" placeholder="Age" name="Age" id="Age"  value={employee.Age} onChange={ onChange }  />  
  53.                             </InputGroup>  
  54.                             <InputGroup className="mb-4">  
  55.             
  56.                               <Input type="text" placeholder="City" name="City" id="City" value={employee.City} onChange={ onChange }  />  
  57.                             </InputGroup>  
  58.                             <InputGroup className="mb-4">  
  59.             
  60.                               <Input type="text" placeholder="Country" name="Country" id="Country" value={employee.Country} onChange={ onChange } />  
  61.                             </InputGroup>  
  62.                             <InputGroup className="mb-4">   
  63.             
  64.                                <Input type="text" placeholder="Gender" name="Gender" id= "Gender" value={employee.Gender} onChange={ onChange } />  
  65.                             </InputGroup>   
  66.                              
  67.                       <CardFooter className="p-4">  
  68.                           <Row>  
  69.                             <Col xs="12" sm="6">  
  70.                               <Button type="submit" className="btn btn-info mb-1" block><span>Save</span></Button>  
  71.                             </Col>  
  72.                             <Col xs="12" sm="6">  
  73.                               <Button className="btn btn-info mb-1" block><span>Cancel</span></Button>  
  74.                             </Col>  
  75.                           </Row>  
  76.                         </CardFooter>  
  77.                           </Form>  
  78.                         </CardBody>                 
  79.                       </Card>  
  80.                     </Col>  
  81.                   </Row>  
  82.                 </Container>  
  83.               </div>  
  84.         )  
  85. }  
  86.   
  87. export default Editemployee  

Create a table in the Database 

 
Open SQL Server Management Studio, create a database named "dbcore ", and in this database, create a table. Give that table a name like "Employees".
  1. CREATE TABLE [dbo].[Employees](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Department] [nvarchar](50) NULL,  
  5.     [Age] [int] NULL,  
  6.     [City] [nvarchar](50) NULL,  
  7.     [Country] [nvarchar](50) NULL,  
  8.     [Gender] [nvarchar](50) NULL,  
  9.  CONSTRAINT [PK_Employees] 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 = ON) ON [PRIMARY]  
  13. ) ON [PRIMARY]  
  14. GO  

Create a Asp.net Web API project

 
Now open Visual Studio and create a new project.
 
CRUD Operations In ReactJS With Hooks
 
Change the name to ReactHooks.
 
CRUD Operations In ReactJS With Hooks
 
Choose the template as Web API.
 
CRUD Operations In ReactJS With Hooks
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
CRUD Operations In ReactJS With Hooks
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
CRUD Operations In ReactJS With Hooks
 
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.
 
CRUD Operations In ReactJS With Hooks
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button. 
 
CRUD Operations In ReactJS With Hooks
 
Now, our data model is successfully created.
 
Right-click on Models folder and add two classes - Emp and Response respectively. Now, paste the following codes in these classes.
 
Emp class
  1. public class Emp  
  2.     {  
  3.         public int Id { getset; }  
  4.         public string Name { getset; }  
  5.         public string Department { getset; }  
  6.         public int Age { getset; }  
  7.         public string City { getset; }  
  8.         public string Country { getset; }  
  9.         public string Gender { getset; }  
  10.     }  
Response Class
  1. public class Response  
  2.     {  
  3.         public string Status { getset; }  
  4.         public string Message { getset; }  
  5.     }  
Right-click on the Controllers folder and add a new controller. Name it as "Hooks controller" and add the following namespace in the Hooks controller. 
  1. using ReactHooks.Models;  
 Now, add a method to insert and update data into the database.
  1. [HttpPost]  
  2.        public object CreateEmp(Emp e)  
  3.        {  
  4.            try  
  5.            {  
  6.                if (e.Id == 0)  
  7.                {  
  8.                    Employee em = new Employee();  
  9.                    em.Name = e.Name;  
  10.                    em.Department = e.Department;  
  11.                    em.Age = e.Age;  
  12.                    em.City = e.City;  
  13.                    em.Country = e.Country;  
  14.                    em.Gender = e.Gender;  
  15.                    DB.Employees.Add(em);  
  16.                    DB.SaveChanges();  
  17.                    return new Response  
  18.                    {  
  19.                        Status = "Success",  
  20.                        Message = "Data save Successfully"  
  21.                    };  
  22.                }  
  23.                else  
  24.                {  
  25.                    var obj = DB.Employees.Where(x => x.Id == e.Id).ToList().FirstOrDefault();  
  26.                    if (obj.Id > 0)  
  27.                    {  
  28.   
  29.                        obj.Name = e.Name;  
  30.                        obj.Department = e.Department;  
  31.                        obj.Age = e.Age;  
  32.                        obj.City = e.City;  
  33.                        obj.Country = e.Country;  
  34.                        obj.Gender = e.Gender;  
  35.                        DB.SaveChanges();  
  36.                        return new Response  
  37.                        {  
  38.                            Status = "Updated",  
  39.                            Message = "Updated Successfully"  
  40.                        };  
  41.                    }  
  42.                }  
  43.            }  
  44.            catch (Exception ex)  
  45.            {  
  46.                Console.Write(ex.Message);  
  47.            }  
  48.            return new Response  
  49.            {  
  50.                Status = "Error",  
  51.                Message = "Data not insert"  
  52.            };  
  53.   
  54.   
  55.        }  
Add the other three methods to delete and fetch data and fetch data by id respectively from the database. 
  1. [HttpGet]  
  2.       [Route("employee")]  
  3.       public object Getrecord()  
  4.   
  5.       {  
  6.           var emp= DB.Employees.ToList();  
  7.           return emp;  
  8.       }  
  1. [HttpDelete]  
  2.     public object Deleteemployee(int id)  
  3.     {  
  4.         var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();  
  5.         DB.Employees.Remove(obj);  
  6.         DB.SaveChanges();  
  7.         return new Response  
  8.         {  
  9.             Status = "Delete",  
  10.             Message = "Delete Successfuly"  
  11.         };  
  12.     }  
  1. [Route("employeedetails")]  
  2.        [HttpGet]  
  3.        public object employeedetailById(int id)  
  4.        {  
  5.            var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();  
  6.            return obj;  
  7.        }  
Complete Hooks 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 ReactHooks.Models;  
  8.   
  9. namespace ReactHooks.Controllers  
  10. {  
  11.     [RoutePrefix("Api/Hooks")]  
  12.     public class HooksController : ApiController  
  13.     {  
  14.         dbCoreEntities DB = new dbCoreEntities();  
  15.         [HttpPost]  
  16.         public object CreateEmp(Emp e)  
  17.         {  
  18.             try  
  19.             {  
  20.                 if (e.Id == 0)  
  21.                 {  
  22.                     Employee em = new Employee();  
  23.                     em.Name = e.Name;  
  24.                     em.Department = e.Department;  
  25.                     em.Age = e.Age;  
  26.                     em.City = e.City;  
  27.                     em.Country = e.Country;  
  28.                     em.Gender = e.Gender;  
  29.                     DB.Employees.Add(em);  
  30.                     DB.SaveChanges();  
  31.                     return new Response  
  32.                     {  
  33.                         Status = "Success",  
  34.                         Message = "Data Successfully"  
  35.                     };  
  36.                 }  
  37.                 else  
  38.                 {  
  39.                     var obj = DB.Employees.Where(x => x.Id == e.Id).ToList().FirstOrDefault();  
  40.                     if (obj.Id > 0)  
  41.                     {  
  42.   
  43.                         obj.Name = e.Name;  
  44.                         obj.Department = e.Department;  
  45.                         obj.Age = e.Age;  
  46.                         obj.City = e.City;  
  47.                         obj.Country = e.Country;  
  48.                         obj.Gender = e.Gender;  
  49.                         DB.SaveChanges();  
  50.                         return new Response  
  51.                         {  
  52.                             Status = "Updated",  
  53.                             Message = "Updated Successfully"  
  54.                         };  
  55.                     }  
  56.                 }  
  57.             }  
  58.             catch (Exception ex)  
  59.             {  
  60.                 Console.Write(ex.Message);  
  61.             }  
  62.             return new Response  
  63.             {  
  64.                 Status = "Error",  
  65.                 Message = "Data not insert"  
  66.             };  
  67.   
  68.   
  69.         }  
  70.   
  71.         [HttpGet]  
  72.         [Route("employee")]  
  73.         public object Getrecord()  
  74.   
  75.         {  
  76.             var emp= DB.Employees.ToList();  
  77.             return emp;  
  78.         }  
  79.   
  80.          
  81.         [HttpDelete]  
  82.         public object Deleteemployee(int id)  
  83.         {  
  84.             var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();  
  85.             DB.Employees.Remove(obj);  
  86.             DB.SaveChanges();  
  87.             return new Response  
  88.             {  
  89.                 Status = "Delete",  
  90.                 Message = "Delete Successfuly"  
  91.             };  
  92.         }  
  93.         [Route("employeedetails")]  
  94.         [HttpGet]  
  95.         public object employeedetailById(int id)  
  96.         {  
  97.             var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();  
  98.             return obj;  
  99.         }  
  100.     }  
  101. }  
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 Vs code and run the project by using following command 'Npm start' and check
 
Enter some data in the textbox and click on save button  
 
CRUD Operations In ReactJS With Hooks
 
Click on Edit button to update values or delete button to delete value 
 
CRUD Operations In ReactJS With Hooks 
CRUD Operations In ReactJS With Hooks
 

Summary

 
In this article, we learned about React hooks and performed CRUD operations using Hooks and Web API. Hooks are a new concept that were introduced in React 16.8. Hooks are an alternative to classes.