In this article, we will learn how to perform CRUD operations in React Js application using the rest API. I think you are now clear about React Js from previous articles about the React Js framework and you are also familiar with creating React Js applications.
If not then please go through the following articles:

In all the above articles I have explained about basics of the React Js. Now after reading the above article I think you are clear about React Js and creating simple React Js applications.

Whenever we are developing the applications we need a database for storing the data.  Here we need to perform CRUD operations in the database table with the help of the rest API.

On various blogs, you can find CRUD operation in React Js. But on many blogs, I have observed they are all using static JSON array to perform the insert update delete in react js.

But in this post, I will explain to you the insert, update, and delete function in the table with the help of the rest API.

insert-update-delete

Rest API

Rest API has been created in Asp .Net Web Api and MsSql.I have table Employees with column Id,EmployeeName,EmployeeSalary and Adress. Now I want to perform crud operation on this table using the Rest API.You can also use these Apis for your practice purpose.

Employee Table

API Base Url-http://virtualsolution.adequateshop.com:168

API EndPoint-

GET: api/Employee

It will return employees in the database

[
{
"$id": "1",
"Id": 1,
"EmployeeName": "Connor",
"EmployeeSalary": 200000,
"Adress": "Amsterdam, Netherlands"
},
{
"$id": "2",
"Id": 3,
"EmployeeName": "John",
"EmployeeSalary": 20000,
"Adress": "Amsterdam, Netherlands"
},
{
"$id": "3",
"Id": 1005,
"EmployeeName": "John Cartor",
"EmployeeSalary": 5000,
"Adress": "Usa"
}
]

 

GET: api/Employee?id=2

It will return all employee by Id in the database

{
"$id": "1",
"Id": 3,
"EmployeeName": "John",
"EmployeeSalary": 20000,
"Adress": "Amsterdam, Netherlands"
}

 

POST: api/Employee

It will create a employee entity in the database

API Request

{
"EmployeeName":"Sammy",
"EmployeeSalary":10000,
"Adress":"Paris, France"
}

API Response 201 created

{
"Id":1005
"EmployeeName":"Sammy",
"EmployeeSalary":10000,
"Adress":"Paris, France"
}

 

PUT: api/Employee?id=2

It will updtae a employee entity in the database

API Request

{
"Id":1005
"EmployeeName":"Sammy New",
"EmployeeSalary":10000,
"Adress":"Paris, France"
}

API Response- 200 Ok

{
"Id":1005
"EmployeeName":"Sammy New",
"EmployeeSalary":10000,
"Adress":"Paris, France"
}

 

DELETE:/api/EmployeeEntities?id=1005
It will delete the employee with id=1005 in the database

CRUD Operation in React Js

Step 1-Create React Js Project with the help of npm

npm init react-crud-operation

1

Step 2-Run below command to install bootstrap and route

npm install react-bootstrap bootstrap
npm install –save react-router-dom

Step 3-Create a “components” folder inside the src folder in our Application.

Step 4-Right-Click “components” folder ->New File and create the class component and I’ll call it Employeelist.js, Addemployee.js, and Editemployee.js

2

3

Step 5- Import all component in our App.js file and define the route for each component

 App.js

import logo from './logo.svg';
import './App.css';
import Employeelist from "./components/Employeelist";
import Editemployee from "./components/Editemployee";
import Addemployee from "./components/Addemployee";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
  return (
    <div className="container body-content">
          <Router>
            <Switch>
              <Route path="/" exact component={Employeelist} />
              <Route path="/editemployee/:id" exact component={Editemployee} />
              <Route path="/addemployee" exact component={Addemployee} />
            </Switch>
          </Router>
    </div>
  );
}

export default App;

Step 6-Now Let’s implement the logic for showing the list of the employee in the organization.
open Employeelist.js Component and copy-paste the below code.

Employeelist.js

import React from 'react';
import { Table, Button, Alert } from 'react-bootstrap';
import { Link } from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.min.css';
const BaseapiUrl = 'http://virtualsolution.adequateshop.com:168';
class Employeelist extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employees: [],
            IsApiError: false
        }
    }

    componentDidMount() {
        debugger;
        fetch(BaseapiUrl + "/api/Employee/")
            .then(res => res.json())
            .then(
                (result) => {
                    debugger;
                    this.setState({
                        employees: result
                    });
                },
                (error) => {
                    this.setState({ IsApiError: true });
                }
            )
    }
    deleteEmployee(EmpId) {
        debugger;
        const { employees } = this.state;
        const apiUrl = BaseapiUrl + "/api/Employee?id="+EmpId;

        fetch(apiUrl, { method: 'DELETE' })
        .then(async response => {
            const data = await response.json();
            // check for error response
            if (!response.ok) {
                // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
            }
            this.setState({
                employees: employees.filter(employee => employee.Id !== EmpId)
            });
            alert('Delete successful');
        })
        .catch(error => {
            alert('There was an error!');
            console.error('There was an error!', error);
        });
    }
    render() {
        var employeeslist = this.state.employees;
        debugger;
        if (employeeslist && employeeslist.length > 0) {
            return (<div>
                <h2>Employees List</h2>
                <Link variant="primary" to="/addemployee">Add Employee</Link>
                {/* {this.state.response.message && <Alert variant="info">{this.state.response.message}</Alert>} */}
                <Table className="table" >
                    <thead>
                        <tr>
                            <th>EmpID</th>
                            <th>Name</th>
                            <th>Salary</th>
                            <th>Address</th>
                        </tr>
                    </thead>
                    <tbody>
                        {employeeslist.map(emp => (
                            <tr key={emp.Id}>
                                <td>{emp.Id}</td>
                                <td>{emp.EmployeeName}</td>
                                <td>{emp.EmployeeSalary}</td>
                                <td>{emp.Adress}</td>
                                <td>
                                    <Link variant="info" to={"/editemployee/" + emp.Id}>Edit</Link>
                                    
                    &nbsp;<Button variant="danger" onClick={() => this.deleteEmployee(emp.Id)}>Delete</Button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </Table>
            </div>)
        }
        else {
            return (<div>No Record Found</div>)
        }
    }
}
export default Employeelist;

employeelist

Step 7-Now Let’s write the logic for adding the employee in the organization.

open Addemployee.js Component and copy-paste the below code.

Addemployee.js

import React, { Component } from "react";
import { Row, Form, Col, Button } from 'react-bootstrap';
import { Link } from "react-router-dom";
const BaseapiUrl = 'http://virtualsolution.adequateshop.com:168';
class Addemployee extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employeeName: '',
            employeeSalary: '',
            employeeAddress: ''
        }
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        const name = event.target.name;
        const value = event.target.value;
        this.setState({
            [name]: value
        })
    }
    AddEmployee() {
        debugger;
        if (this.state.employeeName == "" || this.state.employeeName == undefined) {
            alert("employee Name is required");
        } else if (this.state.employeeSalary == "" || this.state.employeeSalary == undefined) {
            alert("employee Salary is required");
        } else if (this.state.employeeAddress == "" || this.state.employeeAddress == undefined) {
            alert("employee Address  is required");
        }

        let MeetingToken = Math.floor(Math.random() * 100000000 + 1);
        let body = {
            employeeName: this.state.employeeName,
            employeeSalary: this.state.employeeSalary,
            Adress: this.state.employeeAddress
        };

        const requestOptions = {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            },
            body: JSON.stringify(body),
        };

        let baseurl = BaseapiUrl + "/api/Employee/";
        fetch(baseurl, requestOptions)
            .then((res) => {
                return res.json();
            })
            .then((results) => {
                if (results) {
                    alert("Added successfully!");
                    this.setState({
                        employeeName: '',
                        employeeSalary: '',
                        employeeAddress: ''
                    })
                }
            })
            .catch((e) => {
                alert(e);
            });
    }

    render() {
        return (
            <div>
                <h1>Add Employee</h1>
                <Link variant="primary" to="/">View Employee list</Link>
                <Row>
                    <Col sm={6}>
                        <Form onSubmit={this.handleSubmit}>
                            <Form.Group controlId="employeeName">
                                <Form.Label>Employee Name</Form.Label>
                                <Form.Control
                                    type="text"
                                    name="employeeName"
                                    value={this.state.employeeName}
                                    onChange={this.handleChange}
                                    placeholder="Employee Name" />
                            </Form.Group>
                            <Form.Group controlId="employeeSalary">
                                <Form.Label>Employee Salary</Form.Label>
                                <Form.Control
                                    type="text"
                                    name="employeeSalary"
                                    value={this.state.employeeSalary}
                                    onChange={this.handleChange}
                                    placeholder="Employee Salary" />
                            </Form.Group>
                            <Form.Group controlId="employeeAddress">
                                <Form.Label>EmployeeAddress</Form.Label>
                                <Form.Control
                                    type="text"
                                    name="employeeAddress"
                                    value={this.state.employeeAddress}
                                    onChange={this.handleChange}
                                    placeholder="Address" />
                            </Form.Group>
                            <Form.Group>
                                <Button variant="success" onClick={() => this.AddEmployee()}>Save</Button>
                            </Form.Group>
                        </Form>
                    </Col>
                </Row>
            </div>
        )

    }
}
export default Addemployee;

Addemployee

Step 8-Now Let’s write the logic for updating the employee in the organization.

open Editemployee.js Component and copy-paste the below code.

 

import React, { Component } from "react";
import { Row, Form, Col, Button } from 'react-bootstrap';
import { Link } from "react-router-dom";
const BaseapiUrl = 'http://virtualsolution.adequateshop.com:168';
class Editemployee extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employeeName: '',
            employeeSalary: '',
            employeeAddress: ''
        }
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        const name = event.target.name;
        const value = event.target.value;
        this.setState({
            [name]: value
        })

    }
    componentDidMount(props) {
        var Empid = this.props.match.params.id;
        this.GetEmployeeById(Empid);
    }
    GetEmployeeById(Empid) {
        const apiUrl = BaseapiUrl + "api/Employee?id=" + Empid;
        fetch(apiUrl)
            .then(res => res.json())
            .then(
                (result) => {
                    debugger;
                    if (result) {
                        this.setState({
                            employeeName: result.EmployeeName,
                            employeeSalary:result.EmployeeSalary,
                            employeeAddress:result.Adress
                        });
                    }
                    else {
                        alert("employeee record not found!")
                    }
                },
                (error) => {
                    this.setState({ IsApiError: true });
                }
            )
    }

    UpdateEmployee() {
        debugger;
        if (this.state.employeeName == "" || this.state.employeeName == undefined) {
            alert("employee Name is required");
        } else if (this.state.employeeSalary == "" || this.state.employeeSalary == undefined) {
            alert("employee Salary is required");
        } else if (this.state.employeeAddress == "" || this.state.employeeAddress == undefined) {
            alert("employee Address  is required");
        }

        let MeetingToken = Math.floor(Math.random() * 100000000 + 1);
        let body = {
            Id:this.props.match.params.id,
            employeeName: this.state.employeeName,
            employeeSalary: this.state.employeeSalary,
            Adress: this.state.employeeAddress
        };

        const requestOptions = {
            method: 'PUT',
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            },
            body: JSON.stringify(body),
        };

        let baseurl = BaseapiUrl + "/api/Employee?id="+this.props.match.params.id;
        fetch(baseurl, requestOptions)
            .then((res) => {
                return res.json();
            })
            .then((results) => {
                if (results) {
                    alert("Updated successfully!");
                }
            })
            .catch((e) => {
                alert(e);
            });
    }

    render() {
        return (
            <div>
                <h1>Edit Employee</h1>
                <Link variant="primary" to="/">View Employee list</Link>
                <Row>
                    <Col sm={6}>
                        <Form onSubmit={this.handleSubmit}>
                            <Form.Group controlId="employeeName">
                                <Form.Label>Employee Name</Form.Label>
                                <Form.Control
                                    type="text"
                                    name="employeeName"
                                    value={this.state.employeeName}
                                    onChange={this.handleChange}
                                    placeholder="Employee Name" />
                            </Form.Group>
                            <Form.Group controlId="employeeSalary">
                                <Form.Label>Employee Salary</Form.Label>
                                <Form.Control
                                    type="text"
                                    name="employeeSalary"
                                    value={this.state.employeeSalary}
                                    onChange={this.handleChange}
                                    placeholder="Employee Salary" />
                            </Form.Group>
                            <Form.Group controlId="employeeAddress">
                                <Form.Label>EmployeeAddress</Form.Label>
                                <Form.Control
                                    type="text"
                                    name="employeeAddress"
                                    value={this.state.employeeAddress}
                                    onChange={this.handleChange}
                                    placeholder="Address" />
                            </Form.Group>
                            <Form.Group>
                                <Button variant="success" onClick={() => this.UpdateEmployee()}>Save</Button>
                            </Form.Group>
                        </Form>
                    </Col>
                </Row>
            </div>
        )

    }
}
export default Editemployee;

updateemployee

In this post, I have tried to explain the insert, update, and delete action step by step in ReactJS. I have embedded screenshots of each action so that you can easily complete this task on your PC. Believe me, once after this task your understanding of ReactJS, will be improved at a great level.

The post React Js-Insert Update Display Delete CRUD Operations appeared first on Software Development | Programming Tutorials.



Read More Articles