Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data to Database in React.js web application

I'm creating a web application and I'm curious how to send data to MySQL database in it. I have a function that is invoked when user presses button, I want this function somehow to send data to the MySQL server. Does anyone know how to approach this problem? I tried npm MySQL module but it seems the connection doesn't work as it is client side. Is there any other way of doing it? I need an idea to get me started.

Regards

like image 748
Jakub Pro Avatar asked Dec 26 '16 14:12

Jakub Pro


People also ask

Can react directly connect to database?

First, we create a react app, and then for backend maintenance, we create API in node. js and express. js which is running at a different port and our react app running at a different port. for connecting React to the database (MongoDB) we integrate through API.

Can we use database in ReactJS?

The Backendless SDK for JavaScript gives you everything you need to create a backend for your React JS app. You can connect to a real-time database and manage user accounts. You can even send push notifications to your users.


2 Answers

You will need a server that handles requests from your React app and updates the database accordingly. One way would be to use NodeJS, Express and node-mysql as a server:

var mysql = require('mysql');
var express = require('express');
var app = express();

// Set up connection to database.
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'me',
  password: 'secret',
  database: 'my_db',
});

// Connect to database.
// connection.connect();

// Listen to POST requests to /users.
app.post('/users', function(req, res) {
  // Get sent data.
  var user = req.body;
  // Do a MySQL query.
  var query = connection.query('INSERT INTO users SET ?', user, function(err, result) {
    // Neat!
  });
  res.end('Success');
});

app.listen(3000, function() {
  console.log('Example app listening on port 3000!');
});

Then you can use fetch within a React component to do a POST request to the server, somewhat like this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { user: {} };
    this.onSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(e) {
    e.preventDefault();
    var self = this;
    // On submit of the form, send a POST request with the data to the server.
    fetch('/users', { 
        method: 'POST',
        data: {
          name: self.refs.name,
          job: self.refs.job
        }
      })
      .then(function(response) {
        return response.json()
      }).then(function(body) {
        console.log(body);
      });
  }
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <input type="text" placeholder="Name" ref="name"/>
        <input type="text" placeholder="Job" ref="job"/>
        <input type="submit" />
      </form>
    );
  }
}

Keep in mind that this is only one of infinite ways to achieve this.

like image 162
Fabian Schultz Avatar answered Sep 19 '22 23:09

Fabian Schultz


It depends on how your application is organized, I will guess that you have a server that provides your React application code. I would advise you to send the necessary information to your server (if there is any) using a module based on your preferences:

  • fetch built-in XHR api (https://developer.mozilla.org/en/docs/Web/API/Fetch_API)
  • request callback-based npm module (https://www.npmjs.com/package/request)
  • axios promise-based npm module (https://www.npmjs.com/package/axios)

If you are looking for a module/plugin doing all the work from client to database I don't know any and not sure there is because it is usually advised to use a proxy (a server to redirect but also to format or block requests between your client and the database).

Then, in your server you format the necessary information (if any) to be usable by your MySQL database, and then contact your MySQL database with the module of your choice, the first most popular module seems to be: https://www.npmjs.com/package/mysql, but if you know another one or have other preferences go on. (For example with MongoDB we can use Mongoose to make requests easier)

like image 28
mgouault Avatar answered Sep 18 '22 23:09

mgouault