CRUD Operations In ReactJS With Axios Using Web API And SQL Server

In this article, I'm going to perform CRUD operations in ReactJS with Axios using Web API with the help of an example. And the backend is a SQL Server database.

Introduction 

 
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 it. Here is the Visual Studio Code download link: Download Visual Studio Code Editor 
 
Prerequisites
  1. Visual Studio
  2. SQL Server
  3. JS version > 10
  4. React
  5. React Axios
  6. Visual Studio Code
  7. Bootstrap
Step1. Create a database and table
 
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 UserDetails.
 
UserDetails
  1. CREATE TABLE [dbo].[UserDetails](  
  2.     [UserId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FirstName] [varchar](50) NULL,  
  4.     [LastName] [varchar](50) NULL,  
  5.     [EmailId] [varchar](100) NULL,  
  6.     [MobileNo] [varchar](50) NULL,  
  7.     [Address] [varchar](500) NULL,  
  8.     [PinCode] [char](10) NULL,  
  9.  CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED   
  10. (  
  11.     [UserId] ASC  
  12. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  13. ON [PRIMARY]  
  14. GO  
Note
You can choose the size of the columns according to your requirement.
 
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.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
Click OK.
 
Step 3. Add ADO.NET Entity Data Model
 
Now, select the Models folder >> Right-click >> Add >> New Item >> select Data in left panel >> ADO.NET Entity Data Model,
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
Click "Add".
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
Click the "Next" button.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Give the server name of your SQL Server and its credentials then select the database and test connection. Click the OK button.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Click the "Next" button.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Select tables and click the "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.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Click the "Add" button.
 
Now, we will write the logic for performing the CRUD operation. We will go to the Controller class and set the routing to make it more user-friendly by writing the below code.
  1. using System;  
  2. using System.Linq;  
  3. using System.Web.Http;  
  4. using ReactCRUDApi.Models;  
  5.   
  6. namespace ReactCRUDApi.Controllers  
  7. {  
  8.     [RoutePrefix("Api/User")]  
  9.     public class UserController : ApiController  
  10.     {  
  11.         ReactDBEntities objEntity = new ReactDBEntities();  
  12.   
  13.         [HttpGet]  
  14.         [Route("GetUserDetails")]  
  15.         public IQueryable<UserDetail> GetEmaployee()  
  16.         {  
  17.             try  
  18.             {  
  19.                 return objEntity.UserDetails;  
  20.             }  
  21.             catch (Exception)  
  22.             {  
  23.                 throw;  
  24.             }  
  25.         }  
  26.   
  27.         [HttpGet]  
  28.         [Route("GetUserDetailsById/{userId}")]  
  29.         public IHttpActionResult GetUserById(string userId)  
  30.         {  
  31.             UserDetail objUser = new UserDetail();  
  32.             int ID = Convert.ToInt32(userId);  
  33.             try  
  34.             {  
  35.                 objUser = objEntity.UserDetails.Find(ID);  
  36.                 if (objUser == null)  
  37.                 {  
  38.                     return NotFound();  
  39.                 }  
  40.   
  41.             }  
  42.             catch (Exception)  
  43.             {  
  44.                 throw;  
  45.             }  
  46.   
  47.             return Ok(objUser);  
  48.         }  
  49.   
  50.         [HttpPost]  
  51.         [Route("InsertUserDetails")]  
  52.         public IHttpActionResult PostUser(UserDetail data)  
  53.         {  
  54.             string message = "";  
  55.             if (data != null)  
  56.             {  
  57.   
  58.                 try  
  59.                 {  
  60.                     objEntity.UserDetails.Add(data);  
  61.                   int result=  objEntity.SaveChanges();  
  62.                     if(result > 0)  
  63.                     {  
  64.                         message = "User has been sussfully added";  
  65.                     }  
  66.                     else  
  67.                     {  
  68.                         message = "faild";  
  69.                     }  
  70.                 }  
  71.                 catch (Exception)  
  72.                 {  
  73.                     throw;  
  74.                 }  
  75.             }  
  76.   
  77.             return Ok(message);  
  78.         }  
  79.   
  80.         [HttpPut]  
  81.         [Route("UpdateEmployeeDetails")]  
  82.         public IHttpActionResult PutUserMaster(UserDetail user)  
  83.         {  
  84.             string message = "";  
  85.             if (!ModelState.IsValid)  
  86.             {  
  87.                 return BadRequest(ModelState);  
  88.             }  
  89.   
  90.             try  
  91.             {  
  92.                 UserDetail objUser = new UserDetail();  
  93.                 objUser = objEntity.UserDetails.Find(user.UserId);  
  94.                 if (objUser != null)  
  95.                 {  
  96.                     objUser.FirstName = user.FirstName;  
  97.                     objUser.LastName = user.LastName;  
  98.                     objUser.EmailId = user.EmailId;  
  99.                     objUser.MobileNo = user.MobileNo;  
  100.                     objUser.Address = user.Address;  
  101.                     objUser.PinCode = user.PinCode;  
  102.   
  103.                 }  
  104.                 
  105.                 int result = objEntity.SaveChanges();  
  106.                 if (result > 0)  
  107.                 {  
  108.                     message = "User has been sussfully updated";  
  109.                 }  
  110.                 else  
  111.                 {  
  112.                     message = "faild";  
  113.                 }  
  114.   
  115.             }  
  116.             catch (Exception)  
  117.             {  
  118.                 throw;  
  119.             }  
  120.   
  121.             return Ok(message);  
  122.         }  
  123.   
  124.         [HttpDelete]  
  125.         [Route("DeleteUserDetails/{id}")]  
  126.         public IHttpActionResult DeleteUserDelete(int id)  
  127.         {  
  128.             string message = "";  
  129.             UserDetail user = objEntity.UserDetails.Find(id);  
  130.             if (user == null)  
  131.             {  
  132.                 return NotFound();  
  133.             }  
  134.   
  135.             objEntity.UserDetails.Remove(user);  
  136.             int result = objEntity.SaveChanges();  
  137.             if (result > 0)  
  138.             {  
  139.                 message = "User has been sussfully deleted";  
  140.             }  
  141.             else  
  142.             {  
  143.                 message = "faild";  
  144.             }  
  145.   
  146.             return Ok(message);  
  147.         }  
  148.     }  
  149. }  
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 through the below command. But before that, just check if Node and NPM are installed or not. And also, we are using Visual Studio Code for writing the React code for UI application so first, make sure if it's installed or not. If you have not installed it, then go to this link for download.
 
Let's create a React project to open a new terminal. Run the following command to install and create a React project.
 
npx create-react-app crud-app
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
React project has been created.
 
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.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Select folder,
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Step 7. Check react dependency
 
Go to the  package.json file and check the React dependency.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Step 8. Generate React Component
 
Go inside the src folder and create a new folder. Here, I created a UserCRUD folder and created 3 files.
 
AddUser.js
GetUser.js
UserActions.js
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Step 9. Install bootstrap
 
Now, we will install bootstrap to build a beautiful UI of our react application.
 
npm install bootstrap --save
 
Or
 
npm install react-bootstrap bootstrap
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Step 10. Install Axios library
 
Axios is a modern and promise-based JavaScript HTTP client library which works asynchronously and allows us to make HTTP calls and consume REST API.
 
Now, let's install Axios in our React project using the following command.
 
npm install --save axios
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Step 11. Write code in js file to perform our operation
 
Now we will write our logic for performing the 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 the below code.
  1. import React from 'react';  
  2. import { Table,Button } from 'react-bootstrap';  
  3. import axios from 'axios';  
  4.   
  5. const apiUrl = 'http://localhost:51971/Api/User';  
  6.   
  7. class UserList extends React.Component{  
  8.     constructor(props){  
  9.         super(props);  
  10.         this.state = {  
  11.            error:null,  
  12.            users:[],  
  13.            response: {}  
  14.               
  15.         }  
  16.     }  
  17.   
  18.     componentDidMount(){  
  19.        axios.get(apiUrl + '/GetUserDetails').then(response => response.data).then(  
  20.             (result)=>{  
  21.                 this.setState({  
  22.                     users:result  
  23.                 });  
  24.             },  
  25.             (error)=>{  
  26.                 this.setState({error});  
  27.             }  
  28.         )  
  29.     }  
  30.   
  31.       
  32.     deleteUser(userId) {  
  33.       const { users } = this.state;     
  34.      axios.delete(apiUrl + '/DeleteUserDetails/' + userId).then(result=>{  
  35.        alert(result.data);  
  36.         this.setState({  
  37.           response:result,  
  38.           users:users.filter(user=>user.UserId !== userId)  
  39.         });  
  40.       });  
  41.     }  
  42.   
  43.     render(){         
  44.         const{error,users}=this.state;  
  45.         if(error){  
  46.             return(  
  47.                 <div>Error:{error.message}</div>  
  48.             )  
  49.         }  
  50.         else  
  51.         {  
  52.             return(  
  53.          <div>  
  54.                       
  55.                   <Table>  
  56.                     <thead className="btn-primary">  
  57.                       <tr>  
  58.                         <th>First Name</th>  
  59.                         <th>Last Name</th>  
  60.                         <th>EmailId</th>  
  61.                         <th>MobileNo</th>  
  62.                         <th>Address</th>  
  63.                         <th>PinCode</th>  
  64.                         <th>Action</th>  
  65.                       </tr>  
  66.                     </thead>  
  67.                     <tbody>  
  68.                       {users.map(user => (  
  69.                         <tr key={user.UserId}>  
  70.                           <td>{user.FirstName}</td>  
  71.                           <td>{user.LastName}</td>  
  72.                           <td>{user.EmailId}</td>  
  73.                           <td>{user.MobileNo}</td>  
  74.                           <td>{user.Address}</td>  
  75.                           <td>{user.PinCode}</td>  
  76.                           <td><Button variant="info" onClick={() => this.props.editUser(user.UserId)}>Edit</Button>       
  77.                           <Button variant="danger" onClick={() => this.deleteUser(user.UserId)}>Delete</Button>  
  78.                           
  79.                           </td>  
  80.                         </tr>  
  81.                       ))}  
  82.                     </tbody>  
  83.                   </Table>  
  84.                 </div>  
  85.               )  
  86.         }  
  87.     }  
  88. }  
  89.   
  90. export default UserList;  
After that, open the AddUser.js file and first import necessary library and then write the below code.
  1. import React from 'react';  
  2. import { Row, Form, Col, Button } from 'react-bootstrap';  
  3.   
  4. class AddUser extends React.Component {  
  5.   constructor(props) {  
  6.     super(props);  
  7.    
  8.     this.initialState = {  
  9.       UserId: '',  
  10.       FirstName: '',  
  11.       LastName: '',  
  12.       EmailId: '',  
  13.       MobileNo: '',  
  14.       Address: '',  
  15.       PinCode: '',  
  16.     }  
  17.   
  18.     if (props.user.UserId) {  
  19.       this.state = props.user  
  20.     } else {  
  21.       this.state = this.initialState;  
  22.     }  
  23.   
  24.     this.handleChange = this.handleChange.bind(this);  
  25.     this.handleSubmit = this.handleSubmit.bind(this);  
  26.   
  27.   }  
  28.   
  29.   handleChange(event) {  
  30.     const name = event.target.name;  
  31.     const value = event.target.value;  
  32.   
  33.     this.setState({  
  34.       [name]: value  
  35.     })  
  36.   }  
  37.   
  38.   handleSubmit(event) {  
  39.     event.preventDefault();  
  40.     this.props.onFormSubmit(this.state);  
  41.     this.setState(this.initialState);  
  42.   }  
  43.   render() {  
  44.     let pageTitle;  
  45.     let actionStatus;  
  46.     if (this.state.UserId) {  
  47.   
  48.       pageTitle = <h2>Edit User</h2>  
  49.       actionStatus = <b>Update</b>  
  50.     } else {  
  51.       pageTitle = <h2>Add User</h2>  
  52.       actionStatus = <b>Save</b>  
  53.     }  
  54.   
  55.     return (  
  56.       <div>        
  57.         <h2> {pageTitle}</h2>  
  58.         <Row>  
  59.           <Col sm={7}>  
  60.             <Form onSubmit={this.handleSubmit}>  
  61.               <Form.Group controlId="FirstName">  
  62.                 <Form.Label>First Name</Form.Label>  
  63.                 <Form.Control  
  64.                   type="text"  
  65.                   name="FirstName"  
  66.                   value={this.state.FirstName}  
  67.                   onChange={this.handleChange}  
  68.                   placeholder="First Name" />  
  69.               </Form.Group>  
  70.               <Form.Group controlId="LastName">  
  71.                 <Form.Label>Last Name</Form.Label>  
  72.                 <Form.Control  
  73.                   type="text"  
  74.                   name="LastName"  
  75.                   value={this.state.LastName}  
  76.                   onChange={this.handleChange}  
  77.                   placeholder="Last Name" />  
  78.               </Form.Group>  
  79.               <Form.Group controlId="EmailId">  
  80.                 <Form.Label>EmailId</Form.Label>  
  81.                 <Form.Control  
  82.                   type="text"  
  83.                   name="EmailId"  
  84.                   value={this.state.EmailId}  
  85.                   onChange={this.handleChange}  
  86.                   placeholder="EmailId" />  
  87.               </Form.Group>  
  88.               <Form.Group controlId="MobileNo">  
  89.                 <Form.Label>MobileNo</Form.Label>  
  90.                 <Form.Control  
  91.                   type="text"  
  92.                   name="MobileNo"  
  93.                   value={this.state.MobileNo}  
  94.                   onChange={this.handleChange}  
  95.                   placeholder="MobileNo" />  
  96.               </Form.Group>  
  97.               <Form.Group controlId="Address">  
  98.                 <Form.Label>Address</Form.Label>  
  99.                 <Form.Control  
  100.                   type="text"  
  101.                   name="Address"  
  102.                   value={this.state.Address}  
  103.                   onChange={this.handleChange}  
  104.                   placeholder="Address" />  
  105.               </Form.Group>  
  106.   
  107.               <Form.Group controlId="PinCode">  
  108.                 <Form.Label>PinCode</Form.Label>  
  109.                 <Form.Control  
  110.                   type="text"  
  111.                   name="PinCode"  
  112.                   value={this.state.PinCode}  
  113.                   onChange={this.handleChange}  
  114.                   placeholder="PinCode" />  
  115.               </Form.Group>  
  116.               <Form.Group>  
  117.                 <Form.Control type="hidden" name="UserId" value={this.state.UserId} />  
  118.                 <Button variant="success" type="submit">{actionStatus}</Button>            
  119.   
  120.               </Form.Group>  
  121.             </Form>  
  122.           </Col>  
  123.         </Row>  
  124.       </div>  
  125.     )  
  126.   }  
  127. }  
  128.   
  129. export default AddUser;  
Again, open the UserActions.js file and import the necessary library and then write the below code.
  1. import React, { Component } from 'react';  
  2.   
  3. import { Container, Button } from 'react-bootstrap';  
  4. import UserList from './GetUser';  
  5. import AddUser from './AddUser';  
  6. import axios from 'axios';  
  7. const apiUrl = 'http://localhost:51971/Api/User/';  
  8.   
  9. class UserActionApp extends Component {  
  10.   constructor(props) {  
  11.     super(props);  
  12.   
  13.     this.state = {  
  14.       isAddUser: false,  
  15.       error: null,  
  16.       response: {},  
  17.       userData: {},  
  18.       isEdituser: false,  
  19.       isUserDetails:true,  
  20.     }  
  21.   
  22.     this.onFormSubmit = this.onFormSubmit.bind(this);  
  23.   
  24.   }  
  25.   
  26.   onCreate() {  
  27.     this.setState({ isAddUser: true });  
  28.     this.setState({ isUserDetails: false });  
  29.   }  
  30.   onDetails() {  
  31.     this.setState({ isUserDetails: true });  
  32.     this.setState({ isAddUser: false });  
  33.   }  
  34.   
  35.   onFormSubmit(data) {  
  36.     this.setState({ isAddUser: true });  
  37.     this.setState({ isUserDetails: false });  
  38.     if (this.state.isEdituser) {  
  39.      axios.put(apiUrl + 'UpdateEmployeeDetails',data).then(result => {  
  40.       alert(result.data);  
  41.         this.setState({  
  42.           response:result,    
  43.           isAddUser: false,  
  44.           isEdituser: false  
  45.         })  
  46.       });  
  47.     } else {  
  48.      
  49.      axios.post(apiUrl + 'InsertUserDetails',data).then(result => {  
  50.       alert(result.data);  
  51.         this.setState({  
  52.           response:result,    
  53.           isAddUser: false,  
  54.           isEdituser: false  
  55.         })  
  56.       });  
  57.     }  
  58.     
  59.   }  
  60.   
  61.   editUser = userId => {  
  62.   
  63.     this.setState({ isUserDetails: false });  
  64.    axios.get(apiUrl + "GetUserDetailsById/" + userId).then(result => {  
  65.   
  66.         this.setState({  
  67.           isEdituser: true,  
  68.           isAddUser: true,  
  69.           userData: result.data           
  70.         });  
  71.       },  
  72.       (error) => {  
  73.         this.setState({ error });  
  74.       }  
  75.     )  
  76.      
  77.   }  
  78.   
  79.   render() {  
  80.     
  81.     let userForm;  
  82.     if (this.state.isAddUser || this.state.isEditUser) {  
  83.   
  84.       userForm = <AddUser onFormSubmit={this.onFormSubmit} user={this.state.userData} />  
  85.        
  86.     }  
  87.     return (  
  88.       <div className="App">  
  89.  <Container>  
  90.         <h1 style={{ textAlign: 'center' }}>CURD operation in React</h1>  
  91.         <hr></hr>  
  92.         {!this.state.isUserDetails && <Button variant="primary" onClick={() => this.onDetails()}> User Details</Button>}  
  93.         {!this.state.isAddUser && <Button variant="primary" onClick={() => this.onCreate()}>Add User</Button>}  
  94.         <br></br>  
  95.         {!this.state.isAddUser && <UserList editUser={this.editUser} />}  
  96.         {userForm}  
  97.         </Container>  
  98.       </div>  
  99.     );  
  100.   }  
  101. }  
  102. export default UserActionApp;  
And lastly,  open index.js file and import necessary library and then write the below code.
  1. import React from 'react';  
  2. import ReactDOM from 'react-dom';  
  3. import './index.css';  
  4. import * as serviceWorker from './serviceWorker';  
  5. import '../node_modules/bootstrap/dist/css/bootstrap.min.css';  
  6. import UserActionApp from './UserCRUD/UserAction';  
  7. ReactDOM.render(<UserActionApp />, document.getElementById('root'));  
  8. 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.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server 
 
Add namespace
  1. using System.Web.Http.Cors;  
After that, add the below code inside Register method.
  1. var cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  
Step 17. Run
 
We have completed all the needed code 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.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
If we will click Add User button then it will give the below output
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 
Now fill the text boxes and hit the save button.
 
Now do the final operation.
 
CRUD Operations In ReactJS With Axios Using Web API And SQL Server
 

Conclusion

 
We have completed how to perform an operation using React and Axios to get user details, update details, insert details and delete details of a user.
 
We have started by installing and creating the create-react-app then used it to create our React project. Next, we have installed Bootstrap in a React application. After that we installed the Axios client library and used the get(),post(),delete() and put() methods to to HTTP request.
I hope you will enjoy this article. I always welcome any query and comment.