Crud Operation in React.js and MySQL

Crud Operation in React.js and MySQL

Tutorial: “Crud Operation in React.js and MySQL – React Node.js MySQL CRUD Example – Step By Step React, Nodejs and Mysql simple full-stack Application”

In the tutorial, I introduce how to build an “Crud Operation in React.js and MySQL” project with Nodejs RestAPI and the help of Ajax to POST/GET/PUT/DELETE requests with step by step coding examples:

– Nodejs project produces CRUD RestAPIs with MySQL database using the supporting of Sequelize ORM.
– React.js project will consume the Nodejs CRUD RestAPIs by Ajax then show up on Reactjs component’s views.

Related posts:


– I draw a fullstack overview Diagram Architecture from React.js Frontend to MySQL database through Nodejs RestAPI backend.
– Develop Nodejs CRUD RestAPIs with the supporting of Sequelize ORM.
– Implement Reactjs CRUD application with Ajax fetching APIs to do CRUD request (Post/Get/Put/Delete) to Nodejs Backend APIs.
– I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Reactjs to do CRUD requests to Nodejs RestAPIs Server and save/retrieve data to MySQL database.

Crud Operation in React.js and MySQL – Step By Step React, Nodejs and Mysql simple full-stack Application

Overall Architecture System: Crud Operation in React.js and MySQL with Nodejs Example

React.js Nodejs MySQL Diagram Architecture - React Node.js MySQL CRUD Example
React.js Nodejs MySQL Diagram Architecture
  • We build a backend: Nodejs CRUD Application with MySQL that provides RestAPIs for POST/GET/PUT/DELETE data entities and store them in MySQL database.
  • We implement React.js CRUD Application that use Ajax to interact (call/receive requests) with Nodejs CRUD application and display corresponding data in Reactjs Component.

Youtube Video Guide – Crud Operation in React.js and MySQL using Nodejs RestAPI

Nodejs MySQL CRUD Design Application – Crud Operation in React.js and MySQL

Nodejs-Build-CRUD-MySQL-Architecture-Overview
Nodejs-Build-CRUD-MySQL-Architecture-Overview

We have 4 main blocks for the application:

  • For building RestAPIs in Nodejs application, we use Express framework.
  • For interacting with database MySQL, we use Sequelize ORM.
  • We define APIs URL in router.js file
  • We implement how to process each API URL in controller.js file
  • We use Bootstrap and JQuery Ajax to implement frontend client.

Reactjs CRUD Application Design – Crud Operation in React.js and MySQL

Reactjs CRUD RestAPI Application Frontend Architecture Diagram - React Node.js MySQL CRUD Example
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

– Reactjs CRUD Application is designed with 2 main layers:

    React.js components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
    Ajax is used by Reactjs component to fetch (post/put/get/delete) data from remote restapi by http request

Reactjs CRUD Application defines 5 components:

  • Home.js is used serve as the landing page for your app.
  • AppNavbar.js is used to establish a common UI feature between components.
  • CustomerList.js is used to show all customers in the web-page
  • CustomerEdit.js is used to modify the existed customer
  • App.js uses React Router to navigate between components.

Integrative Project Goal – Crud Operation in React.js and MySQL

Reactjs Home page:

Project Goal Home Page - React Node.js MySQL CRUD Example
Project Goal Home Page

Reactjs List all data:

Project Goal Customer List - React Node.js MySQL CRUD Example
Project Goal Customer List

Reactjs add data:

Project Goal - Reactjs Add a Customer through Nodejs RestAPI - React Node.js MySQL CRUD Example
Project Goal – Reactjs Add a Customer through Nodejs RestAPI

Reactjs update data:

Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database
Project Goal – Reactjs Update Customer through Nodejs RestAPI to MySQL database

Reactjs delete a customer with id=2, check the Customer List after deleting:

Project Goal - Reactjs show List Customer after Delete successfully
Project Goal – Reactjs show List Customer after Delete successfully

Check MySQL Database after do CRUD operations:

Check MySQL records after do CRUD operation
Check MySQL records after do CRUD operation

How to Integrate Reactjs with Nodejs? – Crud Operation in React.js and MySQL

For starting to integrate Reactjs with Nodejs project, I recommend you a previous post with detail steps to pratice:

How to Integrate Reactjs with Nodejs Tutorial

React project structure - React Node.js MySQL CRUD Example
React project structure
Check the build production of Reactjs application - React Node.js MySQL CRUD Example
Check the build production of Reactjs application
Integrate successfully between Nodejs RestAPI and Reactjs - React Node.js MySQL CRUD Example
Integrate successfully between Nodejs RestAPI and Reactjs

Nodejs MySQL CRUD RestAPIs Example – Backend Development – CRUD Operation in React.js and MySQL Tutorial

Now it’s time for building the “Crud Operation in React.js and MySQL” project with a set of simple steps:

Let’s go!

Create Nodejs MySQL project – Crud Operation in React.js and MySQL

Before creating a Nodejs project, we need to confirm that the Nodejs and npm had been installed in your computer development by cmd: node -v and npm -v

Check Nodejs environment for development
Check Nodejs environment for development

If these commandlines are not recognized by command prompt, it means you need to install them by visit the https://nodejs.org/en/ site and download installed package and do the nodejs setup for development later.

Now starting development! Create a folder and named it as Nodejs-Reactjs-MySQL, go inside the folder, open a cmd and initiate a Nodejs project by cmd npm init. After all, a package.json file is created as below content:

{
  "name": "nodejs-reactjs-restapi-example",
  "version": "1.0.0",
  "description": "Nodejs Reactjs RestAPI CRUD MySQL database",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/loizenai"
  },
  "keywords": [
    "nodejs",
    "reactjs",
    "crud",
    "mysql"
  ],
  "author": "https://loizenai.com",
  "license": "ISC",
  "dependencies": {
    "body-parse": "^0.1.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.2.5",
    "sequelize": "^6.3.5"
  }
}

For coding Editor, we use friendly Visual Studio Code to write code and debug Nodejs project. For the tutorial, We will create a project with below structure:

Nodejs CRUD MySQL RestAPI project - React Node.js MySQL CRUD Example
Nodejs CRUD MySQL RestAPI project
  1. a file db.config.js is used to define MySQL database configuration with Sequelize ORM
  2. a file customer.model.js is used to define a Sequelize model mapped with corresponding MySQL database table schema.
  3. a file router.js is used to define all Express RestAPI URLs
  4. a file controller.js is used to implement detail logic code to process each incoming request
  5. a file server.js is used to implement a Nodejs Web server

To development a Nodejs CRUD MySQL project, we need a set of packages to handle the full stack of the web backend proccessing, they includes Express framework, Cors, Body Parse, MySQL packages and Sequelize ORM.

$npm install --save express cors body-parser mysql2 sequelize

Nodejs MySQL Database Configuration – Crud Operation in React.js and MySQL

Firstly, we create a file env.js with an const Object to include all configured parameters for MySQL database setup.

const env = {
  database: 'loizenaidb',
  username: 'root',
  password: '12345',
  host: 'localhost',
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};

module.exports = env;

In the tutorial, for the main setting between MySQL database and Sequelize ORM, we define a file db.config.js as below code:

const env = require('./env.js');
 
const Sequelize = require('sequelize');
const sequelize = new Sequelize(env.database, env.username, env.password, {
  host: env.host,
  dialect: env.dialect,
  operatorsAliases: false,
 
  pool: {
    max: env.max,
    min: env.pool.min,
    acquire: env.pool.acquire,
    idle: env.pool.idle
  }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
db.Customer = require('../models/customer.model.js')(sequelize, Sequelize);
 
module.exports = db;

Define Nodejs Sequelize Model – Crud Operation in React.js and MySQL

We need define a Sequelize ORM Model to represent a table in the database. So here is the customer.model.js code:

module.exports = (sequelize, Sequelize) => {
	const Customer = sequelize.define('customer', {	
	  id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
    },
	  firstname: {
			type: Sequelize.STRING
	  },
	  lastname: {
		  type: Sequelize.STRING
  	},
	  address: {
			type: Sequelize.STRING
	  },
	  age: {
			type: Sequelize.INTEGER
    },
    copyright: {
      type: Sequelize.STRING,
      defaultValue: "https://loizenai.com"
    }
	});
	
	return Customer;
}

We create a Sequelize Customer model with 6 attributes for mapping with all corresponding customers table’s columns:

  1. id attribute is a primary key with Int type (in database)
  2. firstname attribute has Sequelize.STRING type mapping with the firstname column in customers table with varchar type
  3. lastname attribute has Sequelize.STRING type mapping with the lastname column in customers table with varchar type
  4. address attribute has Sequelize.STRING type mapping with the lastname column in customers table with varchar type
  5. age attribute has Sequelize.INTEGER type mapping with the age column in customers table with int type
  6. copyrightby attribute has Sequelize.STRING type mapping with the copyrightby column in customers table with varchar type and having default value is https://loizenai.com

Define Express RestAPIs Router – POST/GET/PUT/DELETE – CRUD Operation in React.js and MySQL Tutorial

We define 5 APIs:

  • /api/customer (with POST method) is used to Post a customer to MySQL database
  • /api/customer/:id (with GET method) is used to retrieve a customer from MySQL database with a given id
  • /api/customers (with GET method) is used to retrieve all customers from MySQL database
  • /api/customer (with PUT method) is used to update a customer from MySQL database
  • /api/customer/:id (with DELETE method) is used to remove a customer from MySQL database

Coding:


let express = require('express');
let router = express.Router();
 
const customers = require('../controllers/controller.js');

router.post('/api/customer', customers.createCustomer);
router.get('/api/customer/:id', customers.getCustomer);
router.get('/api/customers', customers.customers);
router.put('/api/customer', customers.updateCustomer);
router.delete('/api/customer/:id', customers.deleteCustomer);

module.exports = router;

Implement RestAPIs Controller – Crud Operation in React.js and MySQL

For processing Post/Get/Put/Delete RestAPI requests, we implement controller.js with 5 functions:

  • exports.createCustomer = (req, res) is used to create a new Customer (post request processing)
  • exports.getCustomer = (req, res) is used to retrieve a Customer with a given id from MySQL database(get request)
  • exports.customers = async (req, res) is used to retrieve all customers
  • exports.updateCustomer = async (req, res) is used to update a customer from MySQL database
  • exports.deleteCustomer = async (req, res) is used to delete a customer from MySQL database

Nodejs Express Post RestAPI request – Add a data to MySQL

exports.createCustomer = (req, res) => {
    let customer = {};

    try{
        // Building Customer object from upoading request's body
        customer.firstname = req.body.firstname;
        customer.lastname = req.body.lastname;
        customer.address = req.body.address;
        customer.age = req.body.age;
    
        // Save to MySQL database
        Customer.create(customer, 
                          {attributes: ['id', 'firstname', 'lastname', 'age', 'address', "copyright"]})
                    .then(result => {    
                      res.status(200).json(result);
                    });
    }catch(error){
        res.status(500).json({
            message: "Fail!",
            error: error.message
        });
    }
}

exports.createCustomer = (req, res) gets a posting customer’s info via request.body object. Then it uses Sequelize to save the customer object to database. After done, it returns a successfully posting message. Otherwise, a error message will be returned.

Nodejs Express Get RestAPI request – retrieve a single data from MySQL

exports.getCustomer = (req, res) => {
    Customer.findByPk(req.params.id, 
                        {attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']})
        .then(customer => {
          res.status(200).json(customer);
        }).catch(error => {
          // log on console
          console.log(error);

          res.status(500).json({
              message: "Error!",
              error: error
          });
        })
}

exports.getCustomer = (req, res) retrieves a customer data from MySQL database with a given id by using Sequelize ORM. After done, it returns a customer object to client. Otherwise, a error message will be returned.

Nodejs Get RestAPI request – retrieve all data from MySQL database

exports.customers = (req, res) => {
    // find all Customer information from 
    try{
        Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']})
        .then(customers => {
            res.status(200).json(customers);
        })
    }catch(error) {
        // log on console
        console.log(error);

        res.status(500).json({
            message: "Error!",
            error: error
        });
    }
}

The function exports.customers = (req, res) retrieves all Customer objects from MySQL database.

Nodejs Delete RestAPI request – delete a data from MySQL with a given id

exports.deleteCustomer = async (req, res) => {
    try{
        let customerId = req.params.id;
        let customer = await Customer.findByPk(customerId);

        if(!customer){
            res.status(404).json({
                message: "Does Not exist a Customer with id = " + customerId,
                error: "404",
            });
        } else {
            await customer.destroy();
            res.status(200);
        }
    } catch(error) {
        res.status(500).json({
            message: "Error -> Can NOT delete a customer with id = " + req.params.id,
            error: error.message
        });
    }
}

The function exports.deleteCustomer = async (req, res) finds a Customer by a given id. If the customer is found, it will be deleted by destroy() function and return back client a successfully message with 200 status code. Otherwise, an error message is returned.

Nodejs Put RestAPI request – update a data from MySQL

exports.updateCustomer = async (req, res) => {
    try{
        let customer = await Customer.findByPk(req.body.id);
    
        if(!customer){
            // return a response to client
            res.status(404).json({
                message: "Not Found for updating a customer with id = " + customerId,
                error: "404"
            });
        } else {    
            // update new change to database
            let updatedObject = {
                firstname: req.body.firstname,
                lastname: req.body.lastname,
                address: req.body.address,
                age: req.body.age
            }
            let result = await Customer.update(updatedObject,
                              { 
                                returning: true, 
                                where: {id: req.body.id},
                                attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']
                              }
                            );

            // return the response to client
            if(!result) {
                res.status(500).json({
                    message: "Error -> Can not update a customer with id = " + req.params.id,
                    error: "Can NOT Updated",
                });
            }

            res.status(200).json(result);
        }
    } catch(error){
        res.status(500).json({
            message: "Error -> Can not update a customer with id = " + req.params.id,
            error: error.message
        });
    }
}

The function exports.updateCustomer = async (req, res) finds a customer object by a given id. If the customer is found, we change the customer attributes with new values retrieving from request.body object. After done, a successfully message will be returned. Otherwise an error message will be returned.

Create Nodejs Express Server.js – Crud Operation in React.js and MySQL

const express = require('express');
const app = express();

var bodyParser = require('body-parser');
 
global.__basedir = __dirname;
 
const db = require('./app/config/db.config.js');

const Customer = db.Customer;

let router = require('./app/routers/router.js');

const cors = require('cors')
const corsOptions = {
  origin: 'http://localhost:4200',
  optionsSuccessStatus: 200
}
app.use(cors(corsOptions));

app.use(bodyParser.json());
app.use(express.static('resources'));
app.use('/', router);

// Create a Server
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

db.sequelize.sync({force: true}).then(() => {
  console.log('Drop and Resync with { force: true }');
  Customer.sync().then(() => {
    const customers = [
      { firstname: 'Jack', lastname: 'Smith', 
                age: 23, address: '374 William S Canning Blvd'},
      { firstname: 'Adam', lastname: 'Johnson', 
                age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'},
      { firstname: 'Dana', lastname: 'Bay', 
                age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'},
    ]
    
    for(let i=0; i<customers.length; i++){
      Customer.create(customers[i]);
    }
  })
}); 

How does the server.js file work?

server.js file will create a Nodejs server’s instance listening at port 8080 and also initiate a MySQL table customers with 3 records.

const express = require('express');
const app = express();
...
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

– For parsing body of requests, we need use body-parser dependency, some below lines of code will be added to server.js file:

...
var bodyParser = require('body-parser');
...
app.use(bodyParser.json());
...
const server = app.listen(8080, function () {
...

We define all RESTAPI URLs in a file router.js and then need attach it with the Express Application:

...
let router = require('./app/routers/router.js');
...
app.use('/', router);
...
const server = app.listen(8080, function () {
...

Backend Testing – Crud Operation in React.js and MySQL using Nodejs Tutorial

MySQL database:

MySQL database records - React Node.js MySQL CRUD Example
MySQL database records

1. Testcase 1 – Get all Customers:

– Nodejs retrieves all customers from MySQL database:

Nodejs Get request Get All Customer from MySQL - React Node.js MySQL CRUD Example
Nodejs Get request Get All Customer from MySQL

2. Testcase 2 – Create a Customer:

– Nodejs posts a new customer to MySQL database:

Nodejs Post request - Post a Customer to MySQL - React Node.js MySQL CRUD Example
Nodejs Post request – Post a Customer to MySQL

3. Testcase 3 – Update a Customer:

– Nodejs updates a customer from MySQL database:

Nodejs PUT request - Update an existing Customer from MySQL - React Node.js MySQL CRUD Example
Nodejs PUT request – Update an existing Customer from MySQL

4. Testcase 4 – Delete a Customer:

– Nodejs delete a Customer from MySQL database:

Nodejs Delete request - Delete a Customer from MySQL database - React Node.js MySQL CRUD Example
Nodejs Delete request – Delete a Customer from MySQL database

Reactjs CRUD Application Overview with Nodejs RestAPIs – Crud Operation in React.js and MySQL

React.js project structure
React.js project structure
Reactjs CRUD RestAPI Application Frontend Architecture Diagram
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

For more details, we go back to the session: Reactjs CRUD Application Overview with Nodejs RestAPIs

How to build Reactjs Application? – Crud Operation in React.js and MySQL

We build a Reactjs Application that fetchs data from MySQL database through MySQL RestAPI with 5 UI components. Step to do:
– Setup Reactjs Application
– Build Reactjs Navigation Bar component
– Build Reactjs Home page component
– Build Reactjs CustomerList Component
– Build Reactjs CustomerEdit Component
– Update Reactjs App.js Component with Router

Setup Reactjs Application with Bootstrap – Crud Operation in React.js and MySQL

Create React App is a command line utility that generates React projects for you. It’s a convenient tool because it also offers commands that will build and optimize your project for production.
The create-react-app will set up everything you need to run a React application.

– Create a new project in the app directory with Yarn.

yarn create react-app app

Project Structure:

Start-Setup-React-project-structure
Start-Setup-React-project-structure

More details you can see at: Create Reactjs Project

After the app creation process completes, navigate into the app directory and install Bootstrap, cookie support for React, React Router, and Reactstrap.

Reactstrap: This library contains React Bootstrap 4 components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript.
– React Router: Components are the heart of React’s powerful, declarative programming model. React Router is a collection of navigational components that compose declaratively with your application.

cd app
yarn add bootstrap@4.1.3 react-cookie@3.0.4 react-router-dom@4.3.1 reactstrap@6.5.0

Build Application Navigation Bar Component – Crud Operation in React.js and MySQL

import React, { Component } from 'react';
import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';

export default class AppNavbar extends Component {
  constructor(props) {
    super(props);
    this.state = {isOpen: false};
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
    return <Navbar color="dark" dark expand="md">
      <NavbarBrand tag={Link} to="/">Home</NavbarBrand>
      <NavbarToggler onClick={this.toggle}/>
      <Collapse isOpen={this.state.isOpen} navbar>
        <Nav className="ml-auto" navbar>
          <NavItem>
            <NavLink
              href="https://loizenai.com">loizenai.com</NavLink>
          </NavItem>
          <NavItem>
            <NavLink href="https://github.com/loizenai">GitHub</NavLink>
          </NavItem>
        </Nav>
      </Collapse>
    </Navbar>;
  }
}

Create Reactjs Home Page Component – Crud Operation in React.js and MySQL

Project Goal Home Page
Project Goal Home Page
import React, { Component } from 'react';
import './App.css';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';
import { Button, Container } from 'reactstrap';

class Home extends Component {
  render() {
    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <Button color="link"><Link to="/customers">Manage Customer List</Link></Button>
        </Container>
      </div>
    );
  }
}

export default Home;

Build Reactjs CustomerList Component – Crud Operation in React.js and MySQL

Project Goal - List Customer after update
Project Goal – List Customer after update

– CustomerList Component will fetch a list of customers from SpringBoot RestAPI api/customers and then shows all of them on a Bootstrap table.
– The CustomerList has 3 buttons:

  • Add Customer & Edit are used to link to a url /customers/new that will map with CustomerEdit component
  • Delete button is used to remove a Customer entity from MySQL data based on a given id through an async function remove(id) that will do a fetch request with DELETE method to SpringBoot RestAPI.

Detail coding:

import React, { Component } from 'react';
import { Button, ButtonGroup, Container, Table } from 'reactstrap';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';

class CustomerList extends Component {

  constructor(props) {
    super(props);
    this.state = {customers: [], isLoading: true};
    this.remove = this.remove.bind(this);
  }

  componentDidMount() {
    this.setState({isLoading: true});

    fetch('api/customers')
      .then(response => response.json())
      .then(data => this.setState({customers: data, isLoading: false}));
  }

  async remove(id) {
    await fetch(`/api/customer/${id}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }).then(() => {
      let updatedCustomers = [...this.state.customers].filter(i => i.id !== id);
      this.setState({customers: updatedCustomers});
    });
  }

  render() {
    const {customers, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    const customerList = customers.map(customer => {
      return <tr key={customer.id}>
        <td style={{whiteSpace: 'nowrap'}}>{customer.firstname}</td>
        <td>{customer.lastname}</td>
        <td>{customer.age}</td>
        <td>{customer.address}</td>
        <td><a href={customer.copyright}>{customer.copyright}</a></td>
        <td>
          <ButtonGroup>
            <Button size="sm" color="primary" tag={Link} to={"/customers/" + customer.id}>Edit</Button>
            <Button size="sm" color="danger" onClick={() => this.remove(customer.id)}>Delete</Button>
          </ButtonGroup>
        </td>
      </tr>
    });

    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <div className="float-right">
            <Button color="success" tag={Link} to="/customers/new">Add Customer</Button>
          </div>
          <h3>Customer List</h3>
          <Table className="mt-4">
            <thead>
              <tr>
                <th width="20%">Firstname</th>
                <th width="20%">Lastname</th>
                <th width="10%">Age</th>
                <th>Address</th>
                <th>Copyrightby</th>
                <th width="10%">Actions</th>
              </tr>
            </thead>
            <tbody>
            {customerList}
            </tbody>
          </Table>
        </Container>
      </div>
    );
  }
}

export default CustomerList;

Build Reactjs CustomerEdit Component – React Node.js MySQL CRUD Example

Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database
Project Goal – Reactjs Update Customer through Nodejs RestAPI to MySQL database

We create a React Form to Put/Post data to MySQL database through SpringBoot RestAPI by using a fetch (PUT/POST) function:

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

After form submition, React Application will come back to a CustomerList component by using a coding-line:

this.props.history.push('/customers');

– Full coding:

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
import AppNavbar from './AppNavbar';

class CustomerEdit extends Component {

  emptyCustomer = {
    firstname: '',
    lastname: '',
    age: '',
    address: '',
    copyrigtby: ''
  };

  constructor(props) {
    super(props);
    this.state = {
      item: this.emptyCustomer
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  async componentDidMount() {
    if (this.props.match.params.id !== 'new') {
      const customer = await (await fetch(`/api/customer/${this.props.match.params.id}`)).json();
      this.setState({item: customer});
    }
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    let item = {...this.state.item};
    item[name] = value;
    this.setState({item});
  }

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

  render() {
    const {item} = this.state;
    const title = <h2>{item.id ? 'Edit Customer' : 'Add Customer'}</h2>;

    return <div>
      <AppNavbar/>
      <Container>
        {title}
        <Form onSubmit={this.handleSubmit}>
          <FormGroup>
            <Label for="firstname">Firstname</Label>
            <Input type="text" name="firstname" id="firstname" value={item.firstname || ''}
                   onChange={this.handleChange} autoComplete="firstname"/>
          </FormGroup>
          <FormGroup>
            <Label for="lastname">Lastname</Label>
            <Input type="text" name="lastname" id="lastname" value={item.lastname || ''}
                   onChange={this.handleChange} autoComplete="lastname"/>
          </FormGroup>          
          <FormGroup>
            <Label for="age">Age</Label>
            <Input type="text" name="age" id="age" value={item.age || ''}
                   onChange={this.handleChange} autoComplete="age"/>
          </FormGroup>
          <FormGroup>
            <Label for="address">Address</Label>
            <Input type="text" name="address" id="address" value={item.address || ''}
                   onChange={this.handleChange} autoComplete="address"/>
          </FormGroup>
          <FormGroup>
            <Button color="primary" type="submit">Save</Button>{' '}
            <Button color="secondary" tag={Link} to="/customers">Cancel</Button>
          </FormGroup>
        </Form>
      </Container>
    </div>
  }
}

export default withRouter(CustomerEdit);

Edit Reactjs App.js Component

App.js uses React Router to navigate between components.

  • path “/” is mapped with Home component
  • path “/customers” is mapped with CustomerList component
  • path “customers/:id” is mapped with CustomerEdit component
import React, { Component } from 'react';
import './App.css';
import Home from './Home';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import CustomerList from './CustomerList';
import CustomerEdit from './CustomerEdit';

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route path='/' exact={true} component={Home}/>
          <Route path='/customers' exact={true} component={CustomerList}/>
          <Route path='/customers/:id' component={CustomerEdit}/>
        </Switch>
      </Router>
    )
  }
}

export default App;

Add a Proxy Setting for calling RestAPIs

To proxy from /api to http://localhost:8080/api, add a proxy setting to app/package.json.

"scripts": {...},
"proxy": "http://localhost:8080",

Integrative Testing: Reactjs Application with Nodejs CRUD RestAPIs + MySQL – React Node.js MySQL CRUD Example (CRUD Operation in React.js and MySQL)

– Run Nodejs project, check MySQL database:

MySQL database records - React Node.js MySQL CRUD Example
MySQL database records

– Start Reactjs Application by cmd: yarn start.

1. Testcase 1: Reactjs Post request – Post data to MySQL through Nodejs RestAPI:

Project Goal - Reactjs Add a Customer through Nodejs RestAPI
Project Goal – Reactjs Add a Customer through Nodejs RestAPI

2. Testcase 2: Reactjs Put request – Put data to MySQL through Nodejs RestAPI:

Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database
Project Goal – Reactjs Update Customer through Nodejs RestAPI to MySQL database

3. Testcase 3: Reactjs Fetch request – Get All data from MySQL through Nodejs RestAPI:

Project Goal List Customer after update
Project Goal List Customer after update

4. Testcase 4: Reactjs Delete request – Delete an entity from MySQL through Nodejs RestAPI:

Delete a Customer with id=2, check the CustomerList after successfully:

Project Goal - Reactjs show List Customer after Delete successfully
Project Goal – Reactjs show List Customer after Delete successfully

– Check MySQL database after doing all CRUD operations:

Check MySQL records after do CRUD operation
Check MySQL records after do CRUD operation

Further Reading – React Node.js MySQL CRUD Example

Related posts:


Sourcecode – Nodejs React.js CRUD Example (React.js + Nodejs + MySQL)

– Full Sourcecode: React.js + Nodejs + MySQL Example

1. Reactjs

React.js-Nodejs-MySQL-CRUD-Example

2. Nodejs RestAPI

Nodejs-Reactjs-MySQL-CRUD-Example

– Github Sourcecode:

1. Reactjs.

Reactjs – Github

2. Nodejs RestAPI:

Nodejs RestAPI – Github



By grokonez | February 2, 2021.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*