2

Using mysqljs, I want to query some data from my local db and render them with react. This is what I did so far:

import React from 'react';
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password: '',
    database: 'pep'
});

connection.connect();
var Menu=React.createClass({
    data : function (){
        connection.query('Select * from '+this.props.table, function(err, rows, fields){
            if(err) throw err;
            console.log(rows);
        })
    },
    render : function () {
        return (
            <div>
                <button onClick={this.data}>click</button>
            </div>
        );
    }
});
export default Menu;

(Another file is using the Menu component and passing the props to Menu)

Nothing is displayed and it came with this error in the bowser's console:

Connection.js:91 Uncaught TypeError: Net.createConnection is not a function
    at Connection.connect (webpack:///./~/mysql/lib/Connection.js?:91:13)
    at eval (webpack:///./src/Menu.js?:24:12)
    at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:2983:2)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:556:30)
    at fn (http://localhost:3000/static/js/bundle.js:87:20)
    at eval (webpack:///./src/Combobox.js?:18:13)
    at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:3121:2)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:556:30)
    at fn (http://localhost:3000/static/js/bundle.js:87:20)
    at eval (webpack:///./src/App.js?:18:17)

Why is that? How can I fix this or what should I do in order to get my data from the db using react?

hhelbawi
  • 141
  • 2
  • 12

1 Answers1

5

mysqljs relies on Node's net library. You don't have this API in your browser, so you won't be able to use the library this way without major changes.

You shouldn't establish a direct connection from the client's browser to your backing database anyway, as your mysql database server is not necessarily built for this use case. Instead, publish your data via a dedicated web server as RESTful web services. You could for example use Node.js and the restify framework for that purpose.

Community
  • 1
  • 1
TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86