In this the article, I'm going to perform CRUD operations in React Js with Axios using Web
API with the help of an example. And backend is a SQL Server database. A Web
API is used to provide data connectivity between the database and the front end
application. On the UI side, I will use bootstrap to create a rich, interactive, device-independent user experience and For building a beautiful UI
I'm
using Visual Studio Code as a tool to build my application. If you don't have
Visual studio code in your system then first you have to download and install.
Here is Visual Studio Code download link: Download
Visual Studio Code Editor
Prerequisites
1 Visual studio
2. SQL Server
3. Node.js version > 10
4. React
5. React Axios
6. Visual studio code
7. Bootstrap
2. SQL Server
3. Node.js version > 10
4. React
5. React Axios
6. Visual studio code
7. Bootstrap
Step1. Create a database and table
Create
a database. Open SQL Server and create a new database and table. As you can see
from the following query, I have created a database table called Branch Details
and Company Details.
UserDetails
CREATE TABLE [dbo].[UserDetails](
[UserId]
[int] IDENTITY(1,1) NOT NULL,
[FirstName]
[varchar](50) NULL,
[LastName]
[varchar](50) NULL,
[EmailId]
[varchar](100) NULL,
[MobileNo]
[varchar](50) NULL,
[Address]
[varchar](500) NULL,
[PinCode]
[char](10) NULL,
CONSTRAINT [PK_UserDetails] PRIMARY
KEY CLUSTERED
(
[UserId]
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
Note
You can choose the size of the column according to your requirements.
You can choose the size of the column according to your requirements.
Step 2.
Create a Web API Project
Now, we will create a Web API with the functionality of binding records from a database. Go to Visual Studio >> File >> New >> Project, and select Web Application. after that, click OK and you will see the templates. Select the Web API template.
Now, we will create a Web API with the functionality of binding records from a database. Go to Visual Studio >> File >> New >> Project, and select Web Application. after that, click OK and you will see the templates. Select the Web API template.
Click Ok
Click OK.
Step 3. Add ADO.NET Entity Data Model
Now, Select Models folder >> Right click >> Add
>> New Item >> select Data in left panel >> ADO.NET Entity Data Model
Click Add button
Click Next button
Give server name of SQL server and it's credential then
select database and test connection then click ok button.
Click Next button
Select tables and click Finish button
Step 4. Add API controller logic
Go to the Controller folder in our API Application and
right-click >> Add >> Controller >> Select Web API 2
Controller-Empty
Now we will write the logic for
performing CRUD operation. We will go to the controller class and set the routing
to make it more user-friendly by writing the below code.
using System;
using System.Linq;
using System.Web.Http;
using ReactCRUDApi.Models;
namespace ReactCRUDApi.Controllers
{
[RoutePrefix("Api/User")]
public class UserController : ApiController
{
ReactDBEntities objEntity = new ReactDBEntities();
[HttpGet]
[Route("GetUserDetails")]
public IQueryable<UserDetail> GetEmaployee()
{
try
{
return objEntity.UserDetails;
}
catch (Exception)
{
throw;
}
}
[HttpGet]
[Route("GetUserDetailsById/{userId}")]
public IHttpActionResult GetUserById(string userId)
{
UserDetail objUser = new UserDetail();
int ID = Convert.ToInt32(userId);
try
{
objUser =
objEntity.UserDetails.Find(ID);
if (objUser == null)
{
return NotFound();
}
}
catch (Exception)
{
throw;
}
return Ok(objUser);
}
[HttpPost]
[Route("InsertUserDetails")]
public IHttpActionResult PostUser(UserDetail data)
{
string message = "";
if (data != null)
{
try
{
objEntity.UserDetails.Add(data);
int result= objEntity.SaveChanges();
if(result > 0)
{
message = "User has been
sussfully added";
}
else
{
message = "faild";
}
}
catch (Exception)
{
throw;
}
}
return Ok(message);
}
[HttpPut]
[Route("UpdateEmployeeDetails")]
public IHttpActionResult PutUserMaster(UserDetail user)
{
string message = "";
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
UserDetail objUser = new UserDetail();
objUser =
objEntity.UserDetails.Find(user.UserId);
if (objUser != null)
{
objUser.FirstName =
user.FirstName;
objUser.LastName =
user.LastName;
objUser.EmailId =
user.EmailId;
objUser.MobileNo =
user.MobileNo;
objUser.Address =
user.Address;
objUser.PinCode =
user.PinCode;
}
int result = objEntity.SaveChanges();
if (result > 0)
{
message = "User has been
sussfully updated";
}
else
{
message = "faild";
}
}
catch (Exception)
{
throw;
}
return Ok(message);
}
[HttpDelete]
[Route("DeleteUserDetails/{id}")]
public IHttpActionResult DeleteUserDelete(int id)
{
string message = "";
UserDetail user = objEntity.UserDetails.Find(id);
if (user == null)
{
return NotFound();
}
objEntity.UserDetails.Remove(user);
int result = objEntity.SaveChanges();
if (result > 0)
{
message = "User has been
successfully deleted";
}
else
{
message = "faild";
}
return Ok(message);
}
}
}
Now, our API has been completed and As you may see from
the above code, it has the functionality to add, replace, update, and delete
records to the table.
Step 5.Create and Install React js
Now we will create a
react project thought below command. But before that just check Node and NPM
installed or not. And also We are using Visual
Studio code as writing angular code for UI application so first, make sure it
installed or not. If you have not installed then go to this link for
download.
Let's create a react
project to open a new terminal and run the following command to install and
create a react project.
npx
create-react-app crud-app
Step 6. Set Visual studio code for react code
Open Visual Studio Code and go inside
the folder and open the project inside the visual studio code.
Select folder
Step 7. Check to react dependency
Go to in package.json file and
check to react dependency.
Step 8. Generate React Component
Go to the inside of the src
folder and create a new folder here I create a UserCRUD folder and create 3 files.
AddUser.js
GetUser.js
UserActions.js
Step 9. Install bootstrap
Now, we will install bootstrap to building a
beautiful UI of our react application.
npm install bootstrap --save
and
npm install react-bootstrap bootstrap
Step 10. Install Axios library
Axios is a modern and promis
based java scrip HTTP client library which is works asynchronously and allows
us to make HTTP calls and consume to REST API.
Now, let's install Axios in our
React project using the following command.
npm install --save
axios
Step 11. Write code in js file to perform our
operation
Now we will write our logic for
performing crud operation. First, we will write code to get user details.
Go inside the UserCRUD folder
and open GetUser.js file and First import necessary library and then write
below code.
import React from 'react';
import { Table,Button } from 'react-bootstrap';
import axios from 'axios';
const apiUrl = 'http://localhost:51971/Api/User';
class UserList extends React.Component{
constructor(props){
super(props);
this.state = {
error:null,
users:[],
response: {}
}
}
componentDidMount(){
axios.get(apiUrl + '/GetUserDetails').then(response => response.data).then(
(result)=>{
this.setState({
users:result
});
},
(error)=>{
this.setState({error});
}
)
}
deleteUser(userId) {
const { users } = this.state;
axios.delete(apiUrl + '/DeleteUserDetails/' + userId).then(result=>{
alert(result.data);
this.setState({
response:result,
users:users.filter(user=>user.UserId !== userId)
});
});
}
render(){
const{error,users}=this.state;
if(error){
return(
<div>Error:{error.message}</div>
)
}
else
{
return(
<div>
<Table>
<thead className="btn-primary">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>EmailId</th>
<th>MobileNo</th>
<th>Address</th>
<th>PinCode</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map(user => (
<tr key={user.UserId}>
<td>{user.FirstName}</td>
<td>{user.LastName}</td>
<td>{user.EmailId}</td>
<td>{user.MobileNo}</td>
<td>{user.Address}</td>
<td>{user.PinCode}</td>
<td><Button variant="info" onClick={() => this.props.editUser(user.UserId)}>Edit</Button>
<Button variant="danger" onClick={() => this.deleteUser(user.UserId)}>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
}
export default UserList;
After that open AddUser.js file
and First import necessary library and then write below code.
import React from 'react';
import { Row, Form, Col, Button } from 'react-bootstrap';
class AddUser extends React.Component {
constructor(props) {
super(props);
this.initialState = {
UserId: '',
FirstName: '',
LastName: '',
EmailId: '',
MobileNo: '',
Address: '',
PinCode: '',
}
if (props.user.UserId) {
this.state = props.user
} else {
this.state = this.initialState;
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
})
}
handleSubmit(event) {
event.preventDefault();
this.props.onFormSubmit(this.state);
this.setState(this.initialState);
}
render() {
let pageTitle;
let actionStatus;
if (this.state.UserId) {
pageTitle = <h2>Edit User</h2>
actionStatus = <b>Update</b>
} else {
pageTitle = <h2>Add User</h2>
actionStatus = <b>Save</b>
}
return (
<div>
<h2> {pageTitle}</h2>
<Row>
<Col sm={7}>
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="FirstName">
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
name="FirstName"
value={this.state.FirstName}
onChange={this.handleChange}
placeholder="First Name" />
</Form.Group>
<Form.Group controlId="LastName">
<Form.Label>Last Name</Form.Label>
<Form.Control
type="text"
name="LastName"
value={this.state.LastName}
onChange={this.handleChange}
placeholder="Last Name" />
</Form.Group>
<Form.Group controlId="EmailId">
<Form.Label>EmailId</Form.Label>
<Form.Control
type="text"
name="EmailId"
value={this.state.EmailId}
onChange={this.handleChange}
placeholder="EmailId" />
</Form.Group>
<Form.Group controlId="MobileNo">
<Form.Label>MobileNo</Form.Label>
<Form.Control
type="text"
name="MobileNo"
value={this.state.MobileNo}
onChange={this.handleChange}
placeholder="MobileNo" />
</Form.Group>
<Form.Group controlId="Address">
<Form.Label>Address</Form.Label>
<Form.Control
type="text"
name="Address"
value={this.state.Address}
onChange={this.handleChange}
placeholder="Address" />
</Form.Group>
<Form.Group controlId="PinCode">
<Form.Label>PinCode</Form.Label>
<Form.Control
type="text"
name="PinCode"
value={this.state.PinCode}
onChange={this.handleChange}
placeholder="PinCode" />
</Form.Group>
<Form.Group>
<Form.Control type="hidden" name="UserId" value={this.state.UserId} />
<Button variant="success" type="submit">{actionStatus}</Button>
</Form.Group>
</Form>
</Col>
</Row>
</div>
)
}
}
export default AddUser;
Again open UserActions.js file
and First import necessary library and then write below code.
import React, { Component } from 'react';
import { Container, Button } from 'react-bootstrap';
import UserList from './GetUser';
import AddUser from './AddUser';
import axios from 'axios';
const apiUrl = 'http://localhost:51971/Api/User/';
class UserActionApp extends Component {
constructor(props) {
super(props);
this.state = {
isAddUser: false,
error: null,
response: {},
userData: {},
isEdituser: false,
isUserDetails:true,
}
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onCreate() {
this.setState({ isAddUser: true });
this.setState({ isUserDetails: false });
}
onDetails() {
this.setState({ isUserDetails: true });
this.setState({ isAddUser: false });
}
onFormSubmit(data) {
this.setState({ isAddUser: true });
this.setState({ isUserDetails: false });
if (this.state.isEdituser) {
axios.put(apiUrl + 'UpdateEmployeeDetails',data).then(result => {
alert(result.data);
this.setState({
response:result,
isAddUser: false,
isEdituser: false
})
});
} else {
axios.post(apiUrl + 'InsertUserDetails',data).then(result => {
alert(result.data);
this.setState({
response:result,
isAddUser: false,
isEdituser: false
})
});
}
}
editUser = userId => {
this.setState({ isUserDetails: false });
axios.get(apiUrl + "GetUserDetailsById/" + userId).then(result => {
this.setState({
isEdituser: true,
isAddUser: true,
userData: result.data
});
},
(error) => {
this.setState({ error });
}
)
}
render() {
let userForm;
if (this.state.isAddUser || this.state.isEditUser) {
userForm = <AddUser onFormSubmit={this.onFormSubmit} user={this.state.userData} />
}
return (
<div className="App">
<Container>
<h1 style={{ textAlign: 'center' }}>CURD operation in React</h1>
<hr></hr>
{!this.state.isUserDetails && <Button variant="primary" onClick={() => this.onDetails()}> User Details</Button>}
{!this.state.isAddUser && <Button variant="primary" onClick={() => this.onCreate()}>Add User</Button>}
<br></br>
{!this.state.isAddUser && <UserList editUser={this.editUser} />}
{userForm}
</Container>
</div>
);
}
}
export default UserActionApp;
And Last open index.js file and First import necessary
library and then write below code.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import UserActionApp from './UserCRUD/UserAction';
ReactDOM.render(<UserActionApp />, document.getElementById('root'));
serviceWorker.unregister();
Finally, Our coding part also
has been completed.
NOTE: I created the onCreate
and onDetails method for navigation purposes. We can also navigate one page to
another page using routing.
Step 16. Set CORS (Cross-Origin Resource
Sharing)
Go to the Web API
project.
Download a NuGet package for
CORS. Go to NuGet Package Manager and download the following file.
After that, go to the App_Start
folder in Web API project and open WebApiConfig.cs class. Here, modify the
Register method with the below code.
Add namespace
using System.Web.Http.Cors;
After that, add the below code inside Register
method.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Step 17. Run
We have completed all
the needed code functionality for our functionality. Before running the
application, first, make sure to save your work.
Now, let's run the app
and see how it works.
Open TERMINAL and
write the following command to run the program.
npm start
The output looks like
the following image. It's a stunning UI that's been created.
If we will click Add
User button then it will give the below output
Now fill the text boxes
and save button.
Now take the final operation.
4 comments:
Thanks for posting. It's an important topic to be read.
React JS training in hyderabad
Hey! This is my first visit to your blog! We are
a collection of volunteers and starting
a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!
React Native Development Company
Reactjs Development Company Texas
Best article, very useful and explanation. Your post is extremely incredible. Thank you very much for the new information.
React Js Online Training in Hyderabad
Best React Js Online Training in Hyderabad
React Js Online Training in Ameerpet
Really awesome blog, Informative and knowledgeable content. Keep sharing more with us.
Mern Stack Training in Hyderabad
Mern Stack Course in Hyderabad
Post a Comment