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.
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.
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
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
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>
<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;
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;
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;
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
- React addons update - how to insert an object into an array of objects?
- React js delete point from the path update the Polygon
- Change to React State doesn't update display in functional component
- Delete task crud in react
- Testing a react component using custom hooks with crud operations functions
- React state update and display new value
- how to delete data from react crud using node js to mongoDB
- Update the display of counting of children according to their state in a React component
- React CRUD operations always using state
- How to display and update deep nested values in React state
- Firestore Security Rules for CRUD Operations React
- How do I update state of a functional component from a class component in order to display items from a map in react
- React - useReducer with asynchronous CRUD operations
- How to update a state entry in react and display it's contents in input field before updating?
- react admin returns Unauthorized 401 error upon CRUD operations
- React form checkbox delete or add, does not update on first interaction
- react admin create update delete not reflected on backend server
- How to update the Material table in react js after CRUD operations?
- React on fetch :: state not reflecting the recent changes in data after ADD or DELETE operations
- I am trying to update the state using the React useState hook?? The Create Read and Delete part has been done but iam not able to update
- How to get the update and delete endpoints to function properly in my React App?
- React Material UI Insert and delete row
- How to update nested state properties in React
- Can't perform a React state update on an unmounted component
- Insert HTML with React Variable Statements (JSX)
- React - Display loading screen while DOM is rendering?
- How to update React Context from inside a child component?
- Update React component every second
- React useEffect causing: Can't perform a React state update on an unmounted component
- How to display svg icons(.svg files) in UI using React Component?
- Learning Redux Thunk. How to trigger action
- A way to access json data
- "TypeError: Object(...) is not a function" react-redux-firebase
- reactstrap fieldset legend not square show
- What is the proper way to show blank menu item for SelectField (material-ui, react)
- React error "You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports"
- Why getting 404 when try to get page via react-router-dom?
- How to get d3 shape constructors to return the type string properly in typescript?
- how pass a var in the axios?
- React Mapping from a Seeds File
- What is the right way to import 3rd party React components into the kotlin.js project?
- Docusaurus MDX rendering
- Warning: Failed prop type: Invalid prop `items[0]` of type `string` supplied to `ImageGallery`, expected `object`
- Remove Unused JS/CSS bundles Code Splitting Webpack
- How do I create a 'All' filter button to filter my products in React?
- google is not defined in react app using create-react-app
- Input value saved in child component's state disappears when the search filter is applied on the parent component
- ReactJS How do i call setState nested Functions
- how to synchronize 2 components(traffic light) that show 2 different colors based on dynamic on/off times
- Working of `useState` function inside `useEffect` function
- I'm using React to retrieve data from Firebase, but the userItem is not defined in my render function why
- React Typescript: Restricting Props setting with dynamic data
- React lazy import statement can't handle expression
- Handle Error response React.js
- React.js Simple component composition issue
- How to Integrate React Components to a legacy app
- Avoid duplicating data (in stores and components) in React Flux app?
- Setting up a counter in a document and then retrieve it using Firestore: Would this be alright or would this be too expensive?
- Redux in npm package
- Display HTML page response in react js
- ReactCSSTransitionGroup not working with controlled Component
- Escape html in react
- How do I update the same object format when I make a new API call in React?
- Hi every one, i got this issue with docker-compose up: it's giving me this Can't find a suitable configuration file in this directory or any
- React Test: Invariant Violation: Element type is invalid: undefined
- Ant Design Tabs remain unchanged when clicking to browser back button. How to change tabs when state updates
- how to add only attribute on tag inside map javascript
- What is the right way for multiple api call?
- React 16: Call children's function from parent when using hooks and functional component
- React - How to Push an Object to an Array Nested within an Array
- Redux on functional components in Reactjs (web)
- What is the easiest way to add <a> tag to a <h1> tag in React?
- State is not updated in StrictMode
- use outer function in useEffect hook get undefined
- Add attributes to React element from string
- Unable to persist the checkboxes
- React Synthetic Event distinguish Left and Right click events
- How to add full page background image in NextJS
- Cannot read property from props in react component
- Why do i get : Must use destructuring state assignment?
- How to trigger onClick of underlayed image?
- Best approach to multilingual react webapp
- Storybook couldn't resolve fs
- Ability to specify existing DynamoDB source when adding GraphQL API
- Styled component with access to React component state?
- I want the arrow icon to flip up and down every time the state changes.and I want to animate it
- React render image from prop
- Laravel not loading React component
- How do I apply a local custom font to Stripe Elements?
- Resetting Values in ReactDOM Ref children (Best Practices?)
- `react-query` mutate onSuccess function not responding
- React Router DOM: Unable to change route to /view from /view/subview
- EventRender renders with wrong position
- On button click i get event of child element
- React useRef with Typescript: Property 'playbackRate' does not exist on type 'HTMLAudioElement'.ts(2339)
- How do i cut an image in half so that it is not seen and that there is no horizontal scrolling?
- Integration test with Cypress or React Testing Library?
- React JS : How To Access Child Component's State Objects From Parent Component
- How to handle "polymorphic" function components
- cors c# web API react
- include foreign libs in clojurescript project
- Call Context function in helper function - React
- React filter still outputting filtered values
- Distinct data in array React
- Changing div width with a button
- pass a list of personas to child component
- React Js : Handle Nested Element In State
- Getting Global Access to URL ID Params
- How can I send React post requet with file data to an API?
- Getting length of list present in state not working
- How can i get errors out of Apollo client in a React front end using GQL
- Simple conditional ES6 Template Literals
- Why is my UI not refreshing after setState()? (using React and Rails)
- Does React only re-rendering what has changed benefit rendering speed?
- generate dynamic tabs from json
- React CSStransition or React-spring in map()
- Enzyme/Jest Context API Injection (React) Not Working
- How i use this style in react... " class[attribute] " [Edited v.2]
- Problem removing event while dialog closed(React useEffect)
- how to re-render React component each and every time freshly with animation
- How to define TypeScript interface for the passed object in props?
- React router v4 - How do you access the state that is passed via Redirect?
- TypeError: this.state.data.map is not a function despite setting data: [ ]
- React useRef changes didn't cause the component rerender which depends on ref.current
- React + Redux : Invariant Violation: Could not find "store" in either the context or props of "Connect(Body)"
- setState for react function component not updated my state
- How to add Image field on right side in bootstrap form
- Cannot display date with react-datepicker with react-hooks-forms on screen
- @material-ui icons react not resolved on windows
- React - 'state' is assigned a value but never used no-unused-vars
- Creating Dynamic Object Keys After mapping on an Array
- Next js api not works on netlify
- Setting Props on React Component dynamically
- React Jest testing : TestingLibraryElementError: Unable to find an element
- Trouble clearing react.useState with clear button
- How to override Material-UI MenuItem selected background color?
- Getting TypeError: Object(...) is not a function with when changing Routes in React
- How send id category in link React?
- How to access cookies from the server in Next.js
- invalid hook call with SWR library
- React - superagent request per mapped item
- Error while formating date with a function
- React Router Won't Work Without Refresh
- State value not updating when passed as route prop
- Appending array with useState hook not working as expected
- Event type for event listener callback function - React & Typescript
- Updated - Changing the state from a functional child component
- I cannot optimize the design for the mobile version
- NextJS - ReferrenceError: document is not defined
- DataTables - Calling functions in 'columnDefs' in react
- Independent scroll time-picker on hover using react-slick
- With Facebook's EventEmitter is there a way to make a late listener receive an event thats already been emitted?
- Is there a way to set the source of the image to font-awesome icon
- How to concatenate a variable and string inside a prop in Javascript?
- url-loader configuration in webpack is loading the images from different path in React JS project
- Material-ui dialog is not closing when overlay is clicked
- Uncaught TypeError: Cannot read property 'value' of null in ReactJS
- Webpack 5 Module federation micro-frontend and react-redux is not working
- Why my images don't loading in the my page?
- Type '{ label: string; value: string; }' is missing the following properties from type in Typescript react js
- opacity of color passed as props Styled component
- I am looking for a way to fix the first column in a table component in react material-ui
- How to test method calls after async call in React/Redux/Jest tests
- React - Login Variables cached in the browser
- Change style of children in MaterialUI only in one element
- Conditional Rendering the components, Next.js style broken on first load
- Check number of active orders in firebase
- Unable to create Stacked Grouped Bar Chart with chart.js / react-chartjs-2 in React
- React router cannot route url with search string
- D3 draw circles around arc
- Display a menu when hovering on the last character in the input in React
- GraphQL Apollo query options do not take defaultProps
- Get value of element in react
- How do I make setState run synchronously in Reactjs?
- React Profiler - Start profiling and reload page?
- React Material UI issue with syled-engine resolution while running tests (Works while serve/building)
- Warning: React does not recognize the `isNarrow` prop on a DOM element - Material UI Component
- How to modify the DOM directly in ReactJS
- material-ui 0.15.2 renders additional vendor-prefixed styles on the server but not the client, leading to React 15.2.1 warnings
- React/Webpack - Image not loading due to wrong path
- Firestore to query by an array's field value
- Load CSS module in ReactJS + Typescript and react rewired
- How to fix React WArning : Can't perform a React state update on an unmounted component
- Saving the state of the function
- problem publishing a package and installing it
- React - difference between function and component
- React Native Circle Image on Android
- How to approach subscriptions in React app
- how to remove the underline of material-ui select?
- Global variables not changing as expected from methods
- How to push to array inside dynamic object using React Hooks?
- In JSX why is this invalid: {...{ type: 'button', ...props }}
- React Uncaught TypeError: canvas.toDataURL is not a function
- My component doesn't re-render after updating Redux store
- How to call script.jsx to make react.js work
- React context api returning undefined when setting the state
- Disabling multiple radio buttons at once
- How to get the block unique ID inside edit and save functions on registerBlockType
- React's props with the same name as their value
- React passing down a function that modifies a third component