In this article, we will learn how to perform CRUD operations in a React.js application using REST API. Assuming you are now familiar with React.js from previous articles discussing the React.js framework, as well as creating React.js applications.

If not then please go through the following articles:

In all the above articles, I have explained the basics of React.js. Now, after reading the above article, I assume you have a clear understanding of React.js and are able to create simple React.js applications.

When developing applications, we often need a database to store data. In this scenario, we need to perform CRUD operations on the database table with the help of a REST API.

While you can find CRUD operation examples in React.js on various blogs, many of them use static JSON arrays to perform insert, update, and delete operations.

However, in this post, I will explain how to perform insert, update, and delete functions in the table using a 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://samplerestapi.com

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

  • The component's state includes an array employees to store the fetched employee data and a boolean IsApiError to track API errors.
  • In the componentDidMount lifecycle method, an API call is made to retrieve the list of employees from the specified URL (BaseapiUrl + "/api/Employee/"). Upon successful response, the retrieved data is stored in the component's state. If an error occurs during the API call, the IsApiError state is set to true.
  • The deleteEmployee method is triggered when a user clicks the delete button associated with an employee. It sends a DELETE request to the API endpoint (BaseapiUrl + "/api/Employee?id=" + EmpId) to delete the employee with the specified ID. If the request is successful, the corresponding employee is removed from the employees array in the state, and an alert message confirms the deletion. If an error occurs during the request, an error alert is displayed.
  • The render method conditionally renders different content based on the presence of employee data (employeeslist). If there are employees available, a table displaying employee details is rendered, including buttons to edit or delete each employee. If no employees are available, a message stating "No Record Found" is displayed.
  • Within the table, each employee's details are mapped to table rows (<tr>) and displayed in table cells (<td>). Edit and delete buttons are provided for each employee, with the delete button's onClick event calling the deleteEmployee method with the respective employee ID.
  • Additionally, a link to add a new employee is included using react-router-dom's Link component, which navigates to the /addemployee route.

The component is exported as Employeelist for use in other parts of the application.

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://samplerestapi.com';
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

  • The component's state includes fields for employeeName, employeeSalary, and employeeAddress, representing the details of the new employee to be added.
  • The handleChange method is invoked whenever there is a change in the input fields. It updates the corresponding state value based on the input field's name.
  • The AddEmployee method is triggered when the user clicks the "Save" button. It performs input validation to ensure that all required fields are filled out. If validation passes, it generates a random MeetingToken and constructs the request body with the employee details.
  • The fetch API is used to send a POST request to the API endpoint (BaseapiUrl + "/api/Employee/") with the request body containing the employee details. Upon receiving a successful response, an alert confirms that the employee has been added, and the input fields are cleared. If an error occurs during the request, an error alert is displayed.
  • In the render method, a form is rendered with input fields for employee name, salary, and address. The onChange event is bound to each input field to update the corresponding state value. The "Save" button triggers the AddEmployee method when clicked.
  • Additionally, a link is provided to navigate back to the employee list using react-router-dom's Link component.


import React, { Component } from "react";
import { Row, Form, Col, Button } from 'react-bootstrap';
import { Link } from "react-router-dom";
const BaseapiUrl = 'http://samplerestapi.com';
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://samplerestapi.com';
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 attempted to explain the insert, update, and delete actions step by step in ReactJS. I have included screenshots of each action to make it easier for you to follow along on your PC. Trust me, completing this task will greatly enhance your understanding of ReactJS.

The component's state includes fields for employeeName, employeeSalary, and employeeAddress, representing the details of the employee to be edited.

The handleChange method is invoked whenever there is a change in the input fields. It updates the corresponding state value based on the input field's name.

The componentDidMount method is called when the component is mounted. It extracts the id parameter from the URL using this.props.match.params.id and fetches the employee details by calling the GetEmployeeById method.

The GetEmployeeById method sends a GET request to the API endpoint (BaseapiUrl + "api/Employee?id=" + Empid) to retrieve the employee details. Upon receiving a successful response, the state is updated with the fetched employee details. If the employee record is not found, an alert is displayed.

The UpdateEmployee method is triggered when the user clicks the "Save" button. It performs input validation to ensure that all required fields are filled out. If validation passes, it generates a random MeetingToken and constructs the request body with the updated employee details.

A PUT request is sent to the API endpoint (BaseapiUrl + "/api/Employee?id="+this.props.match.params.id) with the request body containing the updated employee details. Upon receiving a successful response, an alert confirms that the employee details have been updated.

In the render method, a form is rendered with input fields for editing the employee's name, salary, and address. The onChange event is bound to each input field to update the corresponding state value. The "Save" button triggers the UpdateEmployee method when clicked.