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!
You could look into using web sockets for pushing updates to your front-end.
Basic flow would be:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With