Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Build a Flask React.js Full Stack CRUD REST API in MongoDB & Axios Library Full Project For Beginners

Posted on October 13, 2022

 

 

Welcome folks today in this blog post we will be building a flask react.js full stack crud rest api in MongoDB & Axios Library. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make a new folder and inside that we will make two different folders for frontend and backend as shown below

 

 

mkdir reactflaskcrud

 

 

cd reactflaskcrud

 

 

mkdir backend

 

 

mkdir frontend

 

 

Making the Flask Backend API

 

 

Now we will be making the backend api. For this you need to install the flask library using the pip command as shown below

 

 

pip install flask

 

 

pip install flask_cors

 

 

pip install pymongo

 

 

And we are also installing the cors package of flask which will allow the backend api to be consumed from any frontend. And also we are installing the pymongo package to connect to the MongoDB Database.

 

Now you need to make an app.py file and copy paste the following code

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask_cors import CORS
 
app = Flask(__name__)
client = MongoClient("mongodb://localhost:27017")
# db = client.lin_flask
db = client['reactflaskdb'] ## database name
CORS(app)
 
@app.route('/')
def index():
    return render_template('home.html')
 
if __name__ == '__main__':
    app.debug = True
    app.run()

 

 

So as you can see in the above code we are importing the flask library. From the flask library there is some methods we are importing which is render_template which is used to render out a html template. We are also importing request and jsonify also to make the request and also convert the database records to json. And then we are also importing pymongo to interact with the MongoDB Database. Also we are connecting to the MongoDB Database using the pymongo Library. Here we are providing the mongodb uri. And then we are creating the database reactflaskdb. Here you need to replace your own dataabse name. And then we are also passing the cors middleware to the flask app.

 

And then guys we are making a simple GET Request in this api. When the user visits the homepage then we are showing the home.html file to the user. And then we are starting out the flask app.

 

Now you need to create the templates folder inside the root directory to store all your templates inside your flask app. The directory structure is shown below

 

 

 

 

home.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React.js Flask CRUD REST API</title>
</head>
<body>
    <h1>This is the HomePage of React.js Flask CRUD REST API</h1>
</body>
</html>

 

 

If you run the flask app by running the below command as shown below

 

 

python app.py

 

 

 

 

 

As you can see the flask app has started on port number 5000. You see when you open the app inside the browser. In the homepage we are seeing the home.html template.

 

 

Creating the Users

 

 

Now we will be creating the users using the post request. We will be making the route for this as shown below.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@app.route('/users', methods=['POST', 'GET'])
def data():
    
    # POST a data to database
    if request.method == 'POST':
        body = request.json
        firstName = body['firstName']
        lastName = body['lastName']
        emailId = body['emailId']
        # db.users.insert_one({
        db['users'].insert_one({
            "firstName": firstName,
            "lastName": lastName,
            "emailId":emailId
        })
        return jsonify({
            'status': 'Data is posted to MongoDB!',
            'firstName': firstName,
            'lastName': lastName,
            'emailId':emailId
        })

 

 

Here in this above code we are writing the route for saving data inside the mongodb database. And then we are calling the data() method. First of all we are checking if the request is post or get. If the request is a post request. Then we are extracting the data from the body and converting to json. And then we are extracting the parameters which are passed inside this post request. We are extracting the firstname,lastname and emailId. And then we are inserting the record inside the database using insert_one() method. And then we are returning the json response to the client using the jsonify() method in that we are passing the status and the info about the user. We are passing the firstName,lastName and emailId.

 

 

 

 

 

As you can see we are testing the post route using the postman software. We are passing the raw json where we are providing the details such as emailId, firstName and lastName and then we are making the post request. As we can see we are receiving the json response that the record is inserted successfully.

 

 

 

 

As you can see the record is inserted successfully in the MongoDB Database. As you can see random Id is generated by the MongoDB Database

 

 

Getting the All User Records From MongoDB Database

 

 

Now we will be getting all the records from the MongoDB Database. This will be the get request we will be writing inside the flask app. The code is shown below

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# GET all data from database
    if request.method == 'GET':
        allData = db['users'].find()
        dataJson = []
        for data in allData:
            id = data['_id']
            firstName = data['firstName']
            lastName = data['lastName']
            emailId = data['emailId']
            dataDict = {
                'id': str(id),
                'firstName': firstName,
                'lastName': lastName,
                'emailId': emailId
            }
            dataJson.append(dataDict)
        print(dataJson)
        return jsonify(dataJson)

 

 

As you can see we are again checking if the method request is a GET Request then we are using the find() method inside the pymongo package. And this method returns all the records which are present inside the mongodb database. And then we are appending all the records inside the dictionary. And the using the jsonify() method to convert dictionary to json.

 

 

 

 

As you can see inside the postman we are making a simple GET Request to the /users route to get all the records from the mongoDB Database. And it is returning an array of Objects or records each object has different fields emailId,firstName and lastName.

 

 

Get a Specific User Information Using it’s ID

 

 

Now we will be getting the specific user information using it’s id. The source code is shown below for this request

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@app.route('/users/<string:id>', methods=['GET', 'DELETE', 'PUT'])
def onedata(id):
 
    # GET a specific data by id
    if request.method == 'GET':
        data = db['users'].find_one({'_id': ObjectId(id)})
        id = data['_id']
        firstName = data['firstName']
        lastName = data['lastName']
        emailId = data['emailId']
        dataDict = {
            'id': str(id),
            'firstName': firstName,
            'lastName': lastName,
            'emailId':emailId
        }
        print(dataDict)
        return jsonify(dataDict)

 

 

As you can see we are making the GET request and we are passing the ID as well as a query parameter. And then depending upon the ID given we are returning the information about that specific user. First of all we are checking whether the given request is GET or not. Because as you see we are passing the array of methods such as GET,PUT and DELETE.

 

Now we are using the find_one() method present inside the pymongo module to find the information and we are also passing the id which is given to get the info of that specific user. We are converting the id to ObjectId using ObjectId() method. And then extracting the information and then returning this information to dictionary and sending data as json to the client.

 

Now if I test this route inside the postman. We will making the GET Request passing the id of the user record as shown below

 

 

 

 

Updating a Specific User Information Using it’s ID

 

 

Now we will be updating the information of specific user using it’s ID. For this we will making a PUT Request in the same route as shown below

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# UPDATE a data by id
    if request.method == 'PUT':
        body = request.json
        firstName = body['firstName']
        lastName = body['lastName']
        emailId = body['emailId']
 
        db['users'].update_one(
            {'_id': ObjectId(id)},
            {
                "$set": {
                    "firstName":firstName,
                    "lastName":lastName,
                    "emailId": emailId
                }
            }
        )
 
        print('\n # Update successful # \n')
        return jsonify({'status': 'Data id: ' + id + ' is updated!'})

 

 

As you can see in the above code we are once again checking whether the given request is PUT or not. And then we are extracting the information from the raw json present inside the body. And then we are fetching all the information given in the request of PUT. And then we are updating the user information using the update_one() method. Here in this method we are passing the _id as the first argument and we are converting the id to ObjectId using the ObjectId() method. And then we are secondly passing the user information object which is firstName,lastName and emailId. After that we are retuning the json response to the client passing the status and the id of the user as well.

 

Now we will be testing the PUT Request inside the postman software as shown below to update the user

 

 

As you can see we are receiving the json response from the server. As you can see this time we are using the PUT Request and we are sending the request to the /users route passing the id of the user as query parameter. And then we are setting the raw json header in the body passing the information of the user to be updated

 

 

Deleting a Specific User Using It’s ID

 

 

Now we will be deleting the information of specific user using it’s ID. For this we will making a DELETE Request in the same route as shown below

 

 

Python
1
2
3
4
5
# DELETE a data
    if request.method == 'DELETE':
        db['users'].delete_many({'_id': ObjectId(id)})
        print('\n # Deletion successful # \n')
        return jsonify({'status': 'Data id: ' + id + ' is deleted!'})

 

 

As you can see in the above code we are once again checking whether the given request is DELETE or not. And then we are deleting the user information using the delete_many() method. Here in this method we are passing the _id as the first argument and we are converting the id to ObjectId using the ObjectId() method. After that we are retuning the json response to the client passing the status and the id of the user that the record has been deleted.

 

 

 

 

Full Source Code

 

 

Wrapping it up. Just see the full source code of app.py file as shown below

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask_cors import CORS
 
app = Flask(__name__)
client = MongoClient("mongodb://localhost:27017")
# db = client.lin_flask
db = client['flaskreactdb']
CORS(app)
 
@app.route('/')
def index():
    return render_template('home.html')
 
@app.route('/users', methods=['POST', 'GET'])
def data():
    
    # POST a data to database
    if request.method == 'POST':
        body = request.json
        firstName = body['firstName']
        lastName = body['lastName']
        emailId = body['emailId']
        # db.users.insert_one({
        db['users'].insert_one({
            "firstName": firstName,
            "lastName": lastName,
            "emailId":emailId
        })
        return jsonify({
            'status': 'Data is posted to MongoDB!',
            'firstName': firstName,
            'lastName': lastName,
            'emailId':emailId
        })
    
    # GET all data from database
    if request.method == 'GET':
        allData = db['users'].find()
        dataJson = []
        for data in allData:
            id = data['_id']
            firstName = data['firstName']
            lastName = data['lastName']
            emailId = data['emailId']
            dataDict = {
                'id': str(id),
                'firstName': firstName,
                'lastName': lastName,
                'emailId': emailId
            }
            dataJson.append(dataDict)
        print(dataJson)
        return jsonify(dataJson)
 
@app.route('/users/<string:id>', methods=['GET', 'DELETE', 'PUT'])
def onedata(id):
 
    # GET a specific data by id
    if request.method == 'GET':
        data = db['users'].find_one({'_id': ObjectId(id)})
        id = data['_id']
        firstName = data['firstName']
        lastName = data['lastName']
        emailId = data['emailId']
        dataDict = {
            'id': str(id),
            'firstName': firstName,
            'lastName': lastName,
            'emailId':emailId
        }
        print(dataDict)
        return jsonify(dataDict)
        
    # DELETE a data
    if request.method == 'DELETE':
        db['users'].delete_many({'_id': ObjectId(id)})
        print('\n # Deletion successful # \n')
        return jsonify({'status': 'Data id: ' + id + ' is deleted!'})
 
    # UPDATE a data by id
    if request.method == 'PUT':
        body = request.json
        firstName = body['firstName']
        lastName = body['lastName']
        emailId = body['emailId']
 
        db['users'].update_one(
            {'_id': ObjectId(id)},
            {
                "$set": {
                    "firstName":firstName,
                    "lastName":lastName,
                    "emailId": emailId
                }
            }
        )
 
        print('\n # Update successful # \n')
        return jsonify({'status': 'Data id: ' + id + ' is updated!'})
 
if __name__ == '__main__':
    app.debug = True
    app.run()

 

 

Making the React.js Frontend

 

 

Now guys we will be making the react.js frontend to consume this rest api that we developed in the earlier step using flask. For this you need to initiate a new react.js project inside the backend folder as shown below

 

 

cd backend

 

 

npx create-react-app reactfrontend

 

 

cd frontend

 

 

npm i bootstrap

 

 

npm i axios

 

 

npm i react-router-dom

 

 

As you can see guys we are installing the bootstrap library for making the frontend interface. And then we are also installing axios library which is http client library for making requests to the backend api and lastly we are also installing the react-router-dom library for making the different pages inside react.js using router.

 

If you face any errors just note down the version number of each dependency as shown below in the package.json file. Try to install that specific version of the package to resolve issues

 

 

 

 

 

Directory Structure of React.js Frontend Project

 

 

Now we will be seeing the directory structure of the react.js frontend project which is shown below

 

 

 

 

 

As you can see this is the list of folders and files which will be there inside this react.js project. So first of all we need to go to App.js file of your react.js project and copy paste the below code

 

 

App.js

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import React from 'react';
import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import ListUserComponent from './components/ListUserComponent';
import HeaderComponent from './components/HeaderComponent';
import CreateUserComponent from './components/CreateUserComponent';
import UpdateUserComponent from './components/UpdateUserComponent';
import ViewUserComponent from './components/ViewUserComponent';
 
function App() {
  return (
    <div>
        <Router>
              <HeaderComponent />
                <div className="container">
                    <Switch>
                          <Route path = "/" exact component = {ListUserComponent}></Route>
                          <Route path = "/users" component = {ListUserComponent}></Route>
                          <Route path = "/add-user/:id" component = {CreateUserComponent}></Route>
                          <Route path = "/view-user/:id" component = {ViewUserComponent}></Route>
                          {<Route path = "/update-user/:id" component = {UpdateUserComponent}></Route>}
                    </Switch>
                </div>
        </Router>
    </div>
    
  );
}
 
export default App;

 

 

As you can see guys we are doing the routing here using the react-router-dom. And inside that we have the switch operator to specifically check which route is there. If it is the homepage then we are showing the ListUserComponent. For each Route component inside the Switch operator we are giving the path property and also the component property as well. Path property refers to the actual path in the browser and the component refers to which react.js component will be shown there. And we are importing all the components that will be used at the very top. We will be creating these components one by one later on.

 

 

Writing the Axios HTTP Client Service

 

 

Now we will be making a separate folder called services inside that we will create a UserService.js File and copy paste the below code

 

 

services/UserService.js

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import axios from 'axios';
 
const USER_API_BASE_URL = "http://localhost:5000/users";
 
class UserService {
 
    getUsers(){
        return axios.get(USER_API_BASE_URL);
    }
 
    createUser(user){
        return axios.post(USER_API_BASE_URL, user);
    }
 
    getUserById(userId){
        return axios.get(USER_API_BASE_URL + '/' + userId);
    }
 
    updateUser(user, userId){
        return axios.put(USER_API_BASE_URL + '/' + userId, user);
    }
 
    deleteUser(userId){
        return axios.delete(USER_API_BASE_URL + '/' + userId);
    }
}
 
export default new UserService()

 

 

As you can see we are importing the axios library at the very top to make http requests. And then we are writing the base url of the flask backend api. And then we have a simple class called UserService inside that we have different methods.

 

These methods are used for the crud operations. So first of all we have defined method for getting all Users which is getUsers() here we are making a simple axios get request to the base url. Then we are calling a method to create the user here we are making a axios post request passsing the base url and also the user object in the argument. And then we have the method to get specific details of the user using it’s id. Here we are passing the id of the user to get details using the axios get request. And then we are defining the method taking the id of the user to update the details of the user and here in this method we are also taking the user information object and then making the put request to update the details. And then lastly we are making an axios delete request to delete the user and passing the id as the argument which is actually the delete method.

 

 

Making the Components of App

 

 

Now we will making the components folder inside the project directory. Here first of all we will be making the CRUD Operations component as shown below

 

 

Making the Header Component

 

 

Now first of all guys we will be making the header component of the app. Here in this component we will have a simple header section which will contain the title of the app as shown below

 

 

components/HeaderComponent.js

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React, { Component } from 'react'
import'bootstrap/dist/css/bootstrap.min.css';
class HeaderComponent extends Component {
    constructor(props) {
        super(props)
 
        this.state = {
                
        }
    }
 
    render() {
        return (
            <div>
                <header>
                    <nav className="navbar navbar-dark bg-primary">
                    <div><a href="/users" className="navbar-brand">User Management App</a></div>
                    </nav>
                </header>
            </div>
        )
    }
}
 
export default HeaderComponent

 

 

As you can see we have the nav tag inside this component. And then after that we have the anchor tag which basically routes to the home page of the app. The label is simply the title of the application as shown below

 

 

 

 

Listing out All Users Component

 

 

Now we will be creating the component which will list out all the user’s inside the bootstrap table and also it will contain the update and delete buttons as well.

 

 

components/ListUserComponent.jsx

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import React, { Component } from 'react'
import UserService from '../services/UserService'
 
class ListUserComponent extends Component {
    constructor(props) {
        super(props)
 
        this.state = {
                users: []
        }
        this.addUser = this.addUser.bind(this);
        this.editUser = this.editUser.bind(this);
        this.deleteUser = this.deleteUser.bind(this);
    }
 
    deleteUser(id){
        UserService.deleteUser(id).then( res => {
            this.setState({users: this.state.users.filter(user => user.id !== id)});
        });
    }
    viewUser(id){
        this.props.history.push(`/view-user/${id}`);
    }
    editUser(id){
        this.props.history.push(`/add-user/${id}`);
    }
 
   componentDidMount(){
        UserService.getUsers().then((res) => {
            if(res.data==null)
            {
                this.props.history.push('/add-user/_add');
            }
            this.setState({ users: res.data});
        });
    }
 
    addUser(){
        this.props.history.push('/add-user/_add');
    }
 
    render() {
        return (
            <div>
                 <h2 className="text-center">Users List</h2>
                 <div className = "row">
                    <button className="btn btn-primary" onClick={this.addUser}> Add User</button>
                 </div>
                 <br></br>
                 <div className = "row">
                        <table className = "table table-striped table-bordered">
 
                            <thead>
                                <tr>
                                    <th> User First Name</th>
                                    <th> User Last Name</th>
                                    <th> User Email Id</th>
                                    <th> Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    this.state.users.map(
                                        user =>
                                        <tr key = {user.id}>
                                             <td> { user.firstName} </td>  
                                             <td> {user.lastName}</td>
                                             <td> {user.emailId}</td>
                                             <td>
                                                 <button onClick={ () => this.editUser(user.id)} className="btn btn-info">Update </button>
                                                 <button style={{marginLeft: "10px"}} onClick={ () => this.deleteUser(user.id)} className="btn btn-danger">Delete </button>
                                                 <button style={{marginLeft: "10px"}} onClick={ () => this.viewUser(user.id)} className="btn btn-info">View </button>
                                             </td>
                                        </tr>
                                    )
                                }
                            </tbody>
                        </table>
 
                 </div>
 
            </div>
        )
    }
}
 
export default ListUserComponent

 

 

As you can see this is a class level react.js component. Inside this component we are showing the list of users inside the bootstrap table. Inside the constructor of the component we are initializing the empty users array and then we are importing the userService which contains all the methods to fetch all the users from the mongodb database.

 

And also we have the update and delete buttons as well to each record inside the table. When we click the update and delete button we are calling the deleteUser() and updateUser() method. Inside the componentDidMount() method we are fetching all the users using the service method to get all the user records from the mongodb database. And then we are receiving the json data and setting the empty users state array to the json data we received.

 

 

 

Creating the Users Component

 

 

Now we will be defining the component to create the user records using the simple html5 form as shown below.

 

 

components/CreateUserComponent.jsx

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import React, { Component } from 'react'
import UserService from '../services/UserService';
 
class CreateUserComponent extends Component {
    constructor(props) {
        super(props)
 
        this.state = {
            // step 2
            id: this.props.match.params.id,
            firstName: '',
            lastName: '',
            emailId: ''
        }
        this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
        this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
        this.saveOrUpdateUser = this.saveOrUpdateUser.bind(this);
    }
 
    // step 3
    componentDidMount(){
 
        // step 4
        if(this.state.id === '_add'){
            return
        }else{
            UserService.getUserById(this.state.id).then( (res) =>{
                let user = res.data;
                this.setState({firstName: user.firstName,
                    lastName: user.lastName,
                    emailId : user.emailId
                });
            });
        }        
    }
    saveOrUpdateUser = (e) => {
        e.preventDefault();
        let user = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
        console.log('user => ' + JSON.stringify(user));
 
        // step 5
        if(this.state.id === '_add'){
            UserService.createUser(user).then(res =>{
                this.props.history.push('/users');
            });
        }else{
            UserService.updateUser(user, this.state.id).then( res => {
                this.props.history.push('/users');
            });
        }
    }
    
    changeFirstNameHandler= (event) => {
        this.setState({firstName: event.target.value});
    }
 
    changeLastNameHandler= (event) => {
        this.setState({lastName: event.target.value});
    }
 
    changeEmailHandler= (event) => {
        this.setState({emailId: event.target.value});
    }
 
    cancel(){
        this.props.history.push('/users');
    }
 
    getTitle(){
        if(this.state.id === '_add'){
            return <h3 className="text-center">Add User</h3>
        }else{
            return <h3 className="text-center">Update User</h3>
        }
    }
    render() {
        return (
            <div>
                <br></br>
                   <div className = "container">
                        <div className = "row">
                            <div className = "card col-md-6 offset-md-3 offset-md-3">
                                {
                                    this.getTitle()
                                }
                                <div className = "card-body">
                                    <form>
                                        <div className = "form-group">
                                            <label> First Name: </label>
                                            <input placeholder="First Name" name="firstName" className="form-control"
                                                value={this.state.firstName} onChange={this.changeFirstNameHandler}/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Last Name: </label>
                                            <input placeholder="Last Name" name="lastName" className="form-control"
                                                value={this.state.lastName} onChange={this.changeLastNameHandler}/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Email Id: </label>
                                            <input placeholder="Email Address" name="emailId" className="form-control"
                                                value={this.state.emailId} onChange={this.changeEmailHandler}/>
                                        </div>
 
                                        <button className="btn btn-success" onClick={this.saveOrUpdateUser}>Save</button>
                                        <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
                                    </form>
                                </div>
                            </div>
                        </div>
 
                   </div>
            </div>
        )
    }
}
 
export default CreateUserComponent

 

 

As you can see inside this component we are rendering a simple html5 form to enter the details of the user. And then if we click the save button we are inserting the record in the mongodb database. At the top we are again importing the userService that contains the method to save the user. Inside this method we are making a axios post request to the backend flask api. And after that we are redirecting the client to the /users route.

 

 

 

 

View Specific User Details in Card Component

 

 

Now we will writing the component which will show the details of the specific user using it’s id. Here we are rendering all the details of the user inside the bootstrap card as shown below

 

 

components/ViewUserComponent.jsx

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import React, { Component } from 'react'
import UserService from '../services/UserService'
 
class ViewUserComponent extends Component {
    constructor(props) {
        super(props)
 
        this.state = {
            id: this.props.match.params.id,
            user: {}
        }
    }
 
    componentDidMount(){
        UserService.getUserById(this.state.id).then( res => {
            this.setState({user: res.data});
        })
    }
 
    render() {
        return (
            <div>
                <br></br>
                <div className = "card col-md-6 offset-md-3">
                    <h3 className = "text-center"> View User Details</h3>
                    <div className = "card-body">
                        <div className = "row">
                            <label> User First Name: </label>
                            <div> { this.state.user.firstName }</div>
                        </div>
                        <div className = "row">
                            <label> User Last Name: </label>
                            <div> { this.state.user.lastName }</div>
                        </div>
                        <div className = "row">
                            <label> User Email ID: </label>
                            <div> { this.state.user.emailId }</div>
                        </div>
                    </div>
 
                </div>
            </div>
        )
    }
}
 
export default ViewUserComponent

 

 

And here in the above code we are rendering out all the details inside the bootstrap card. Here at the top once again we are importing the userService file which contains the axios get request to get details of specific user passing the id of the user. And then we are setting the state of the user with the json response we received from the server.

 

 

Updating the User Details Component

 

 

Now guys we will be creating the component where we will be updating the user details using the html5 form. The code is shown below

 

 

components/UpdateUserComponent.jsx

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import React, { Component } from 'react'
import UserService from '../services/UserService';
 
class UpdateUserComponent extends Component {
    constructor(props) {
        super(props)
 
        this.state = {
            id: this.props.match.params.id,
            firstName: '',
            lastName: '',
            emailId: ''
        }
        this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
        this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
        this.updateUser = this.updateUser.bind(this);
    }
 
    componentDidMount(){
        UserService.getUserById(this.state.id).then( (res) =>{
            let user = res.data;
            this.setState({firstName: user.firstName,
                lastName: user.lastName,
                emailId : user.emailId
            });
        });
    }
 
    updateUser = (e) => {
        e.preventDefault();
        let user = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
        console.log('user => ' + JSON.stringify(user));
        console.log('id => ' + JSON.stringify(this.state.id));
        UserService.updateUser(user, this.state.id).then( res => {
            this.props.history.push('/users');
        });
    }
    
    changeFirstNameHandler= (event) => {
        this.setState({firstName: event.target.value});
    }
 
    changeLastNameHandler= (event) => {
        this.setState({lastName: event.target.value});
    }
 
    changeEmailHandler= (event) => {
        this.setState({emailId: event.target.value});
    }
 
    cancel(){
        this.props.history.push('/users');
    }
 
    render() {
        return (
            <div>
                <br></br>
                   <div className = "container">
                        <div className = "row">
                            <div className = "card col-md-6 offset-md-3 offset-md-3">
                                <h3 className="text-center">Update User</h3>
                                <div className = "card-body">
                                    <form>
                                        <div className = "form-group">
                                            <label> First Name: </label>
                                            <input placeholder="First Name" name="firstName" className="form-control"
                                                value={this.state.firstName} onChange={this.changeFirstNameHandler}/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Last Name: </label>
                                            <input placeholder="Last Name" name="lastName" className="form-control"
                                                value={this.state.lastName} onChange={this.changeLastNameHandler}/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Email Id: </label>
                                            <input placeholder="Email Address" name="emailId" className="form-control"
                                                value={this.state.emailId} onChange={this.changeEmailHandler}/>
                                        </div>
 
                                        <button className="btn btn-success" onClick={this.updateUser}>Save</button>
                                        <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
                                    </form>
                                </div>
                            </div>
                        </div>
 
                   </div>
            </div>
        )
    }
}
 
export default UpdateUserComponent

 

 

As you can see we have the simple bootstrap html5 form where we have the input fields to update the user details. And we have the button of update to update the details. Again at the top we are importing the userService which contains the updateUser method. Here we are passing the id of the user to be updated and also passing a object containing the details of the user to be updated.

 

 

 

 

As you can see if you click the update button then inside this above html5 form all the details of that specific user will be auto filled and populated as shown above.

 

Recent Posts

  • Build a JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • React-Admin Example to Create CRUD REST API Using JSON-Server Library in Browser Using Javascript
  • Javascript Papaparse Example to Parse CSV Files and Export to JSON File and Download it as Attachment
  • Javascript Select2.js Example to Display Single & Multi-Select Dropdown & Fetch Remote Data Using Ajax in Dropdown
  • Video.js Video Player Plugin Library in Javascript For Playing Videos in Browser
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme