Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update React Data when MySQL Data Changes

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!

like image 470
Matt Avatar asked Dec 20 '18 15:12

Matt


1 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
like image 182
jonnyg Avatar answered Nov 13 '22 00:11

jonnyg