'How to connect MySQL database to ReactJS app?

I have build a Todo App with create-react-app. The store I'm using is based on Local Storage(JS attribute of object window). Now I created a MySQL databases and want to connect to that database, so the state will show the values from database, and will be updated through actions.

I've tried to connect to db and output values through 'node' console using db.js. It works.

const mysql = require('mysql');

const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root",
  database: 'root'
});

con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM tasks", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

Is it possible to connect the state of app to database using this script?



Solution 1:[1]

You can't connect them directly.

JavaScript running in a web browser cannot speak the MySQL protocol (nor can it make raw network connections that would be needed to write an implementation in JS).

Instead, create a web service (in the programming language of your choice, which could be JavaScript running on Node.js (e.g. the code you have already + Express.js + some glue)) and use Ajax to communicate with it.

Solution 2:[2]

The general solution for a question like this is the following framework:

  • Back-end (Node.js, Express, Database connection including authorization)
  • Front-end (React(, Redux to manage state))

If you then launch the React app, it should populate its state based on data retrieved from the database, which is a process to which you can add authorization (make retrievable data depend on the role/status of the user).

In the back-end you can define functions that take in a certain subset of parameters, which performs database actions, to which you can add business rules for your application. The React app then just sends HTTP requests to the Express server, which handles everything that needs verification and authorization before even touching the data.

If you search the internet for any configuration of a fullstack architecture using React and MySQL, you'll find similar results to what I mentioned.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Thomas Brok