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
- Visual Studio
- SQL Server
- JS version > 10
- React
- React Axios
- Visual Studio Code
- 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
- 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 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.
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,
Click "Add".
Click the "Next" button.
Give the server name of your SQL Server and its credentials then select the database and test connection. Click the OK button.
Click the "Next" button.
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.
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.
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
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.
Select folder,
Step 7. Check react dependency
Go to the package.json file and check the React dependency.
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
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
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
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.
- 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 the AddUser.js file and first import necessary library and then write the 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 the UserActions.js file and import the necessary library and then write the 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 lastly, open index.js file and import necessary library and then write the 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. 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 hit the save button.
Now do the final operation.
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.