React.js Crud Example with Web API - Nodejs + MySQL
react
23
WebAPI
2
node
17
Mysql
86
Male avatar

loveprogramming viết ngày 13/03/2021

Tutorial: https://grokonez.com/react-js-crud-web-api-nodejs-mysql

Tutorial: "React.js crud example with Web API usign Axios library - Step By Step with React, Nodejs/Express Sequelize and Mysql simple full-stack Application"

In the tutorial, I introduce how to build an “React.js Nodejs CRUD MySQL Example - CRUD Operation in React.js and MySQL” project with 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.

React Node.js Mysql CRUD Example - Step By Step React, Nodejs and Mysql simple full-stack Application

Overall Architecture System: React.js Crud Example with Web API

[caption id="attachment_3912" align="alignnone" width="654"]React.js Nodejs MySQL Diagram Architecture - React.js crud example with Web API React.js Nodejs MySQL Diagram Architecture[/caption]

  • 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 - React.js Crud Example with Web API

Nodejs MySQL CRUD Design Application - React.js Crud Example with Web API

[caption id="attachment_3913" align="alignnone" width="689"]Nodejs-Build-CRUD-MySQL-Architecture-Overview - React.js crud example with Web API Nodejs-Build-CRUD-MySQL-Architecture-Overview[/caption]

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 - React.js Crud Example with Web API

[caption id="attachment_3914" align="alignnone" width="691"]Reactjs CRUD RestAPI Application Frontend Architecture Diagram - React.js crud example with Web API Reactjs CRUD RestAPI Application Frontend Architecture Diagram[/caption]

– 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 - React.js Crud Example with Web API

Reactjs Home page:

[caption id="attachment_3915" align="alignnone" width="481"]Project Goal Home Page - React.js crud example with Web API Project Goal Home Page[/caption]

Reactjs List all data:

[caption id="attachment_3916" align="alignnone" width="810"]Project Goal Customer List - React.js crud example with Web API Project Goal Customer List[/caption]

Reactjs add data:

[caption id="attachment_3917" align="alignnone" width="518"]Project Goal - Reactjs Add a Customer through Nodejs RestAPI - React Node.js MySQL CRUD Example Project Goal - Reactjs Add a Customer through Nodejs RestAPI[/caption]

Reactjs update data:

[caption id="attachment_3918" align="alignnone" width="524"]Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database[/caption]

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

[caption id="attachment_3919" align="alignnone" width="759"]Project Goal - Reactjs show List Customer after Delete successfully Project Goal - Reactjs show List Customer after Delete successfully[/caption]

Check MySQL Database after do CRUD operations:

[caption id="attachment_3920" align="alignnone" width="805"]Check MySQL records after do CRUD operation - React.js crud example with Web API Check MySQL records after do CRUD operation[/caption]

How to Integrate Reactjs with Nodejs?

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

[caption id="attachment_3923" align="alignnone" width="686"]React project structure - React Node.js MySQL CRUD Example React project structure[/caption]

[caption id="attachment_3924" align="alignnone" width="413"]Check the build production of Reactjs application - React Node.js MySQL CRUD Example Check the build production of Reactjs application[/caption]

[caption id="attachment_3925" align="alignnone" width="498"]Integrate successfully between Nodejs RestAPI and Reactjs - React.js crud example with Web API Integrate successfully between Nodejs RestAPI and Reactjs[/caption]

Nodejs MySQL CRUD RestAPIs Example – Backend Development - React.js Crud Example with Web API

Now it’s time for building the “Nodejs MySQL CRUD RestAPIs Example” project with a set of simple steps:

Let’s go!

Create Nodejs MySQL project - React.js Crud Example with Web API

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

[caption id="attachment_3926" align="alignnone" width="505"]Check Nodejs environment for development Check Nodejs environment for development[/caption]

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:

[caption id="attachment_3927" align="alignnone" width="750"]Nodejs CRUD MySQL RestAPI project - React Node.js MySQL CRUD Example Nodejs CRUD MySQL RestAPI project[/caption]

  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 - React.js Crud Example with Web API

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 - React.js Crud Example with Web API

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

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 - React.js Crud Example with Web API

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 - React.js Crud Example with Web API

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 - React.js Crud Example with Web API

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 – Nodejs MySQL CRUD RestAPIs testsuite - React.js Crud Example with Web API

MySQL database:

[caption id="attachment_3928" align="alignnone" width="711"]MySQL database records - React Node.js MySQL CRUD Example MySQL database records[/caption]

  1. Testcase 1 – Get all Customers:
  • Nodejs retrieves all customers from MySQL database:

[caption id="attachment_3929" align="alignnone" width="578"]Nodejs Get request Get All Customer from MySQL - React.js crud example with Web API Nodejs Get request Get All Customer from MySQL[/caption]

  1. Testcase 2 – Create a Customer:

– Nodejs posts a new customer to MySQL database:

[caption id="attachment_3930" align="alignnone" width="626"]Nodejs Post request - Post a Customer to MySQL - React Node.js MySQL CRUD Example Nodejs Post request - Post a Customer to MySQL[/caption]

  1. Testcase 3 – Update a Customer:
  • Nodejs updates a customer from MySQL database:

[caption id="attachment_3931" align="alignnone" width="600"]Nodejs PUT request - Update an existing Customer from MySQL - React.js crud example with Web API Nodejs PUT request - Update an existing Customer from MySQL[/caption]

  1. Testcase 4 – Delete a Customer:
  • Nodejs delete a Customer from MySQL database:

[caption id="attachment_3932" align="alignnone" width="796"]Nodejs Delete request - Delete a Customer from MySQL database - React Node.js MySQL CRUD Example Nodejs Delete request - Delete a Customer from MySQL database[/caption]

Reactjs CRUD Application Overview with Nodejs RestAPIs

[caption id="attachment_3933" align="alignnone" width="374"]React.js project structure - React.js crud example with Web API React.js project structure[/caption]

[caption id="attachment_3934" align="alignnone" width="691"]Reactjs CRUD RestAPI Application Frontend Architecture Diagram Reactjs CRUD RestAPI Application Frontend Architecture Diagram[/caption]

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

How to build Reactjs Application? - React.js Crud Example with Web API

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 - React.js Crud Example with Web API

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:

[caption id="attachment_3935" align="alignnone" width="686"]Start-Setup-React-project-structure - React.js crud example with Web API Start-Setup-React-project-structure[/caption]

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

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 - React.js Crud Example with Web API

[caption id="attachment_3915" align="alignnone" width="481"]Project Goal Home Page Project Goal Home Page[/caption]

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

[caption id="attachment_3876" align="alignnone" width="753"]Project Goal - List Customer after update Project Goal - List Customer after update[/caption]

  • 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

[caption id="attachment_3918" align="alignnone" width="524"]Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database[/caption]

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 - React.js Crud Example with Web API

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 - React.js Crud Example with Web API

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.js Crud Example with Web API

  • Run Nodejs project, check MySQL database:

[caption id="attachment_3936" align="alignnone" width="711"]MySQL database records - React.js crud example with Web API MySQL database records[/caption]

  • Start Reactjs Application by cmd: yarn start.
  1. Testcase 1: Reactjs Post request - Post data to MySQL through Nodejs RestAPI:

[caption id="attachment_3937" align="alignnone" width="518"]Project Goal - Reactjs Add a Customer through Nodejs RestAPI Project Goal - Reactjs Add a Customer through Nodejs RestAPI[/caption]

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

[caption id="attachment_3938" align="alignnone" width="524"]Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database[/caption]

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

[caption id="attachment_3941" align="alignnone" width="753"]Project Goal List Customer after update - React.js crud example with Web API Project Goal List Customer after update[/caption]

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

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

[caption id="attachment_3940" align="alignnone" width="759"]Project Goal - Reactjs show List Customer after Delete successfully Project Goal - Reactjs show List Customer after Delete successfully[/caption]

  • Check MySQL database after doing all CRUD operations:

[caption id="attachment_3942" align="alignnone" width="805"]Check MySQL records after do CRUD operation Check MySQL records after do CRUD operation[/caption]

Further Reading - React.js Crud Example with Web API

Related posts:

Sourcecode - React.js Crud Example with Web API

  • Full Sourcecode: React.js + Nodejs + MySQL Example
  1. Reactjs

React.js-Nodejs-MySQL-CRUD-Example

  1. Nodejs RestAPI

Nodejs-Reactjs-MySQL-CRUD-Example

  • Github Sourcecode:
  1. Reactjs.

Reactjs - Github

  1. Nodejs RestAPI:

Nodejs RestAPI - Github

https://grokonez.com/react-js-crud-web-api-nodejs-mysql

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

451 bài viết.
79 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
Bài viết liên quan
White
8 0
Lời tựa Chỉ mới tuần trước thôi, cộng đồng developer trên thế giới đã "dậy sóng" khi Apple thông báo sẽ KHÔNG hỗ trợ 16 Web API cho trình duyệt Saf...
luongvanphuc viết 9 tháng trước
8 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
451 bài viết.
79 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!