Crud using React js and web api

Crud using React js and web api

Crud using React js and web api

Prerequisites

  • Basic knowledge of React.js and Web API.
  • Visual Studio should be installed on your system.
  • SQL Server Management Studio.
  • Basic knowledge of React strap and HTML.

Create a ReactJS Project

Let's create a React app by using the following command:

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. 

npm install --save bootstrap    

npm install --save reactstrap react react-dom

Now, open the index.js file and add import Bootstrap.

import 'bootstrap/dist/css/bootstrap.min.css';

Now, install the Axios library by using the following command. 

npm install --save axios

Now, go to the src folder,  create a new folder, and inside this folder, add three new components:

  • Createemployee.js.
  • Editemployee.js.
  • EmployeList.js.

Add Routing in ReactJS

Install the react-router-dom package by using the following command:

npm install react-router-dom --save

Open the app.js file and import Router, Route (react-router-dom), and the three components

import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

import Createemployee from './CrudComponent/Createemployee';  

     import EmployeList from './CrudComponent/EmployeList';  
     import Editemployee from "./CrudComponent/Editemployee"; 

 

Add the following code in the app.js file:

import React from 'react';  
 
import logo from './logo.svg';  
 
import './App.css';  
 
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
 
import Createemployee from './CrudComponent/Createemployee'  
 
import EmployeList from './CrudComponent/EmployeList'  
 
import Editemployee from "./CrudComponent/Editemployee";  
 
function App() {  
 
  return (  
 
    <div className="App">  
 
     <Router>    
 
      <div className="container">    
 
        <nav className="btn btn-warning navbar navbar-expand-lg navheader">    
 
          <div className="collapse navbar-collapse" >    
 
           
 
            <ul className="navbar-nav mr-auto">    
 
              <li className="nav-item">    
 
                <Link to={'/Createemployee'} className="nav-link">Add Employee</Link>    
 
              </li>    
 
              <li className="nav-item">    
 
                <Link to={'/EmployeList'} className="nav-link">Employee List</Link>    
 
              </li>    
 
            </ul>    
 
          </div>    
 
        </nav> <br />    
 
        <Switch>    
 
          <Route exact path='/Createemployee' component={Createemployee} />    
 
          <Route path='/edit/:id' component={Editemployee} />    
 
          <Route path='/EmployeList' component={EmployeList} />    

         </Switch>    

 
      </div>    
 
    </Router>   
    </div>    
  );  
}  
export default App; 

Now, open the Createemployee.js file and add the following code:

import React, { useState, useEffect } from 'react'  

import axios from 'axios';  
 
import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
 
function Createemployee(props) {  
 
  const [employee, setemployee] = useState({ Name: '', Department: '', Age: '', City: '', Country: '', Gender: '' });  
 
  const [showLoading, setShowLoading] = useState(false);  
 
  const apiUrl = "http://localhost:62168/api/Hooks/CreateEmp";  
 
  
 
  const Insertemployee = (e) => {  
 
    e.preventDefault();  
 
    debugger;  
 
    const data = { Name:employee.Name, Department: employee.Department, Age: employee.Age, City:employee.City, Country: employee.Country, Gender: employee.Gender };  
 
    axios.post(apiUrl, data)  
 
      .then((result) => {  
 
        props.history.push('/EmployeList')  
 
      });  
 
  };  
 
  const onChange = (e) => {  
 
    e.persist();  
 
    debugger;  
 
    setemployee({...employee, [e.target.name]: e.target.value});  
 
  }  
 
  
 
  return (  
 
    <div className="app flex-row align-items-center">  
 
      <Container>  
 
        <Row className="justify-content-center">  
 
          <Col md="12" lg="10" xl="8">  
 
            <Card className="mx-4">  
 
              <CardBody className="p-4">  
3                < 
 
                  <h1>Register</h1>  
 
                  <InputGroup className="mb-3">  
 
  
 
                    <Input type="text" name="Name" id="Name" placeholder="Name" value={employee.Name} onChange={ onChange/>  
                  </InputGroup>  
                   <InputGroup className="mb-3">  
  
                    <Input type="text" placeholder="Department" name="Department" id="Department" value={employee.Department}   onChange={ onChange }/>  
 
                  </InputGroup>  
 
                  <InputGroup className="mb-3">  
 
  
 
                    <Input type="text" placeholder="Age" name="Age" id="Age"  value={employee.Age} onChange={ onChange }  />  
 
                  </InputGroup>  
 
                  <InputGroup className="mb-4">  
 
  
 
                    <Input type="text" placeholder="City" name="City" id="City" value={employee.City} onChange={ onChange }  />  
 
                  </InputGroup>  
 
                  <InputGroup className="mb-4">  
 
  
 
                    <Input type="text" placeholder="Country" name="Country" id="Country" value={employee.Country} onChange={ onChange } />  
 
                  </InputGroup>  
 
                  <InputGroup className="mb-4">   
 
  
 
                     <Input type="text" placeholder="Gender" name="Gender" id= "Gender" value={employee.Gender} onChange={ onChange } />  
 
                  </InputGroup>   
 
             <CardFooter className="p-4">  
 
                <Row>  
 
                  <Col xs="12" sm="6">  
 
                    <Button type="submit" className="btn btn-info mb-1" block><span>Save</span></Button>  
 
                  </Col>  
 
                  <Col xs="12" sm="6">  
 
                    <Button className="btn btn-info mb-1" block><span>Cancel</span></Button>  
 
                  </Col>  
 
                </Row>  
 
              </CardFooter>  
 
                </Form>  
 
              </CardBody>  
 
            </Card>  
 
          </Col>  
 
        </Row>  
 
      </Container>  
 
    </div>  
 
  )  
 
}  
 
export default Createemployee  

Now, open the EmployeList.js file and add the following code:


	
import React from 'react'  
import { Badge, Card, CardBody, CardHeader, Col, Pagination, PaginationItem, PaginationLink, Row, Table } from 'reactstrap';  
 
import axios from 'axios';  
 
import { useState, useEffect } from 'react'  
 
function EmployeList(props) {  
 
  const [data, setData] = useState([]);  
 
  
 
  useEffect(() => {  
 
    const GetData = async () => {  
 
      const result = await axios('http://localhost:62168/api/hooks/employee');  
 
      setData(result.data);  
 
    };  
 
  
 
    GetData();  
 
  }, []);  
 
  const deleteeployee = (id) => {  
 
    debugger;  
 
    axios.delete('http://localhost:62168/api/hooks/Deleteemployee?id=' + id)  
 
      .then((result) => {  
 
        props.history.push('/EmployeList')  
 
      });  
 
  };  
 
  const editemployee = (id) => {  
 
    props.history.push({  
 
      pathname: '/edit/' + id  
 
    });  
 
  };  
 
  
 
  return (  
 
    <div className="animated fadeIn">  
 
      <Row>  
 
        <Col>  
 
          <Card>  
 
            <CardHeader>  
 
              <i className="fa fa-align-justify"></i> Employee List  
 
              </CardHeader>  
 
            <CardBody>  
 
              <Table hover bordered striped responsive size="sm">  
 
                <thead>  
 
                  <tr>  
 
                    <th>Name</th>  
 
                    <th>Department</th>  
 
                    <th>Age</th>  
 
                    <th>City</th>  
 
                    <th>Country</th>  
 
                    <th>Gender</th>  
 
                    <th>Action</th>  
 
                  </tr>  
 
                </thead>  
 
                <tbody>  
 
                  {  
 
                    data.map((item, idx) => {  
 
                      return <tr>  
 
                        <td>{item.Name}</td>  
 
                        <td>{item.Department}</td>  
 
                        <td>{item.Age}</td>  
 
                        <td>{item.City}</td>  
 
                        <td>{item.Country}</td>  
 
                        <td>  
 
                          {item.Gender}  
 
                        </td>  
 
                        <td>  
 
                          <div class="btn-group">  
 
                            <button className="btn btn-warning" onClick={() => { editemployee(item.Id) }}>Edit</button>  
 
                            <button className="btn btn-warning" onClick={() => { deleteeployee(item.Id) }}>Delete</button>  
 
                          </div>  
 
                        </td>  
 
                      </tr>  
 
                    })}  
 
                </tbody>  
 
              </Table>  
 
            </CardBody>  
 
          </Card>  
 
        </Col>  
 
      </Row>  
 
    </div>  
 
  )  
 
}  
 
  
 
export default EmployeList 

Now, open the Editemployee.js file and add the following code:

import React, { useState, useEffect } from 'react'  

 
import axios from 'axios';  
 
import { Button, Card, CardBody, CardFooter, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';  
 
function Editemployee(props) {  
 
        const [employee, setemployee]= useState({Id:'',Name: '', Department: '', Age: '', City: '', Country: '', Gender: '' });  
 
        const Url = "http://localhost:62168/api/Hooks/employeedetails?id=" + props.match.params.id;  
 
        
 
        useEffect(() => {  
 
          const GetData = async () => {  
            const result = await axios(Url);  
 
            setemployee(result.data);  
 
            
 
          };  
 
        
 
          GetData();  
 
        }, []);  
 
        
 
        const UpdateEmployee = (e) => {  
 
          e.preventDefault();  
 
          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 };  
 
          axios.post('http://localhost:62168/api/Hooks/CreateEmp', data)  
 
            .then((result) => {  
 
              props.history.push('/EmployeList')  
 
            });  
 
        };  
 
        
 
        const onChange = (e) => {  
 
          e.persist();  
 
          setemployee({...employee, [e.target.name]: e.target.value});  
 
        }  
 
        
 
        return (  
 
                <div className="app flex-row align-items-center">  
 
                <Container>  
 
                  <Row className="justify-content-center">  
 
                    <Col md="12" lg="10" xl="8">  
 
                      <Card className="mx-4">  
 
                        <CardBody className="p-4">  
 
                          <Form onSubmit={UpdateEmployee}>  
 
                            <h1>Update Employee</h1>  
 
                        
 
                            <InputGroup className="mb-3">  
 
            
 
                              <Input type="text" name="Name" id="Name" placeholder="Name" value={employee.Name} onChange={ onChange }  />  
 
                            </InputGroup>  
 
                             <InputGroup className="mb-3">  
 
            
 
                              <Input type="text" placeholder="Department" name="Department" id="Department" value={employee.Department} onChange={ onChange }/>  
 
                            </InputGroup>  
 
                            <InputGroup className="mb-3">  
 
            
 
                              <Input type="text" placeholder="Age" name="Age" id="Age"  value={employee.Age} onChange={ onChange }  />  
 
                            </InputGroup>  
 
                            <InputGroup className="mb-4">  
            
 
                              <Input type="text" placeholder="City" name="City" id="City" value={employee.City} onChange={ onChange }  />  
 
                            </InputGroup>  
 
                            <InputGroup className="mb-4">  
 
            
 
                              <Input type="text" placeholder="Country" name="Country" id="Country" value={employee.Country} onChange={ onChange } />  
 
                            </InputGroup>  
 
                            <InputGroup className="mb-4">   
 
            
 
                               <Input type="text" placeholder="Gender" name="Gender" id= "Gender" value={employee.Gender} onChange={ onChange } />  
 
                            </InputGroup>   
 
                             
 
                      <CardFooter className="p-4">  
 
                          <Row>  
 
                            <Col xs="12" sm="6">  
 
                              <Button type="submit" className="btn btn-info mb-1" block><span>Save</span></Button>  
 
                            </Col>  
 
                            <Col xs="12" sm="6">  
 
                              <Button className="btn btn-info mb-1" block><span>Cancel</span></Button>  
 
                            </Col>  
 
                          </Row>  
 
                        </CardFooter>  
 
                          </Form>  
 
                        </CardBody>                 
 
                      </Card>  
 
                    </Col>  
 
                  </Row>  
 
                </Container>  
 
              </div>  
 
        )  
 
}  
 
  
 
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."

CREATE TABLE [dbo].[Employees](  

 
    [Id] [int] IDENTITY(1,1) NOT NULL,  
 
    [Name] [nvarchar](50) NULL,  
 
    [Department] [nvarchar](50) NULL,  
 
    [Age] [int] NULL,  
 
    [City] [nvarchar](50) NULL,  
 
    [Country] [nvarchar](50) NULL,  
 
    [Gender] [nvarchar](50) NULL,  
 
 CONSTRAINT [PK_Employees] 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 

Create a Asp.net Web API project

Now, open Visual Studio and create a new project. Change the name to ReactHooks. Select the Web API template.

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> dataClick 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, select database name on the next page, and click OK.

Check the Table checkbox. The internal options will be selected by default. Now, click the Finish button. 

 

Now, our data model is successfully created.

Right-click the Models folder and add two classes — Emp and Response. Now, paste the following codes in these classes:

Emp class

public class Emp  

 
    {  
 
        public int Id { get; set; }  
 
        public string Name { get; set; }  
 
        public string Department { get; set; }  
 
        public int Age { get; set; }  
 
        public string City { get; set; }  
 
        public string Country { get; set; }  
 
        public string Gender { get; set; }  
 
    }  

 

Right-click the Controllers folder and add a new controller. Name it "Hooks controller" and add the following namespace in the Hooks controller: Now, add a method to insert and update data into the database.

[HttpPost]  

 
       public IActionResult CreateEmp(Emp e)  
 
       {  
 
           try  
 
           {  
 
               if (e.Id == 0)  
 
               {  
 
                   Employee em = new Employee();  
 
                   em.Name = e.Name;  
1                   e. 
                   em.Age = e.Age;  
 
                   em.City = e.City;  
 
                   em.Country = e.Country;  
 
                   em.Gender = e.Gender;  
 
                   DB.Employees.Add(em);  
                   DB.SaveChanges();  
                   return Ok(new { Status = "Success", Message="Added Successfully"});                     
 
               }  
 
               else  
 
               {  
 
                   var obj = DB.Employees.Where(x => x.Id == e.Id).ToList().FirstOrDefault();  
 
                   if (obj.Id > 0)  
 
                   {  
 
  
 
                       obj.Name = e.Name;  
 
                       obj.Department = e.Department;  
 
                       obj.Age = e.Age;  
 
                       obj.City = e.City;  
 
                       obj.Country = e.Country;  
 
                       obj.Gender = e.Gender;  
 
                       DB.SaveChanges();  
 
                       return Ok(new { Status = "Success", Message="Updated Successfully"});           
 
                   }  
 
               }  
 
           }  
 
           catch (Exception ex)  
 
           {  
 
               Console.Write(ex.Message);  
 
           }  

            return Ok(new { Status = "Error", Message="Failed to add the data"});          

 
  
 
       }  

 

Add the other three methods to delete and fetch data and fetch data by id from the database. 

[HttpGet]

[Route("employee")]  

 
      public IActionResult Getrecord()  
 
  
 
      {  
 
          var emp= DB.Employees.ToList();  
 
          return Ok(emp);  
 
      }  

 

    [HttpDelete]  
 
    public IActionResult Deleteemployee(int id)  
 
    {  
 
        var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();  
 
        DB.Employees.Remove(obj);  
 
        DB.SaveChanges();  

        return Ok(new { Status = "Delete", Message="Deleted Successfully"});          

 
    }  

 

      [Route("employeedetails")]  
 
       [HttpGet]  
 
       public IActionResult employeedetailById(int id)  
 
       {  
 
           var obj = DB.Employees.Where(x => x.Id == id).ToList().FirstOrDefault();  
 
           return Ok(obj);  
 
       }

 

Now, let's enable CORS. Go to Tools, open the 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 VS Code and run the project by using following command Npm start and check the port that you have your application running on. 


 

Enter some data in the textbox and click on the Save button.

Click the Edit button to update values or the Delete button to delete the value. 

 


Posted By:

Kunal Arora

Chief Technology Officer at Lionzy Infotech Solutions (LIS). He is a Blogger, Web and Mobile Apps Programmer and Digital Marketer by Profession. He is Passionate about New Technologies and trends running in the Corporate World.

0 Comments

Leave a Comment