Update React Data when MySQL Data Changes

Viewed 16804

I've created a React application which uses fetch() to the route file on componentDidMount to build out data in the rendered component.

This works great, but the React component is static when the data in the MySQL database is updated.

How do I update my React component with any changes when the data in the MySQL database is changed? Please see an example of my code below.

React File - react.js

class myComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        }
    }

    // componentDidMount - When the component is mounted.
    componentDidMount() {

        // Retrieve project data from the database.
        fetch('/retrieve-data', {
            credentials: 'include'
        })
        .then((response) => {
            if (response.ok) {
                return response.json();
            } else {
                console.log('Error with session response');
            }
        })
        .then((result) => {

            // Set the state of data.
            this.setState({
                data: data
            })
        })
        .catch((error) => {
            console.log('Error: ', error);
        });
    }

    render() {
        return (
            <div>

                {/* Loop Data Array */}
                {this.state.data.map((thisData, k) => (
                    <div key={k}>
                        {thisData.field1}
                    </div>
                ))}

            </div>
        )
    }
}

Route File - retrieve-data.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var connection = mysql.createConnection({
    host: myHost,
    user: myUser,
    password: myPassword,
    database: myDatabase
})

router.get('/', function(req, res, next) {

    // Select data from the database.
    connection.query("SELECT * FROM database_table", function (error, resultData, fields) {

        // Send the result message back to the React application.
        res.send({resultData});
    });
});

module.exports = router;

The data is updated by a Webhook on a separate route file, so this could be where I would want the server to tell React that it needs to update, but only if the change was relative to the data the individual client is seeing.

Apologies for this question, I am very new to React. Thank you!

3 Answers

You could look into using web sockets for pushing updates to your front-end.

Basic flow would be:

  1. Broadcast message from your server to React client when data changes
  2. Listen for the ‘dataChanged’ event in React, and update React’s state accordingly when this is received

https://www.npmjs.com/package/socket.io

You could use socket.io to relay the changes.

Non-conventional approach would be to setup a front-end loop that checks every so often for changes and updates the DOM, but that can get resource intensive when you have many users on the website.

While you can use Web Sockets, as suggested by @jonnyg, and in fact that is the more performant approach, that requires being familiar with Web Sockets and will require changes on the server.

A simpler approach you can implement on the client side would be to implement a polling system, whereby you basically keep "asking" the server for the data every x seconds and see if it changed.

You can do this by creating a setInterval timer which will make your network request every x seconds.

Related