2

I make my first web application with nodes and reacc. I do sql query in node.js and show html elements in my page. I need help getting the result of sql in my html page as json date. I put some of the code with my experiments, which may be very wrong. Regards.

var React = require('react');
var DefaultLayout = require('./layout/master');

var mysql = require('mysql');

var connection = mysql.createConnection({
    port: '3301',
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'nodedb',
});
connection.connect();

function getArticless() {
    connection.query('select * from articles', function(err, result) {
        if (err) 
            JSON.stringify(err);
        else
            JSON.stringify(result);
    });
}

const jsonArticles = getArticless();

var IndexComponent = React.createClass({
    render: function() {
        return (
            <DefaultLayout name={this.props.name}>
                <div>
                    {jsonArticles }
                </div>
            </DefaultLayout>
        )
    }
});

module.exports = IndexComponent;

2
  • From your code that you posted it is very unclear what you are trying to achieve. It looks as tho you are calling the db from the client, or else you are attempting to use react to render from the server. Furthermore, you are not accounting for the fact that the db query happens asynchronously. This code seems riddled with bugs. Perhaps you can try to narrow down an area where you need help and ask that as a question. Commented Apr 30, 2017 at 19:49
  • I want to use react to render from the server. Commented Apr 30, 2017 at 20:03

1 Answer 1

1

I am not familiar with the nuances of server side rendering with react, however there is one glaring issue that stands out with your code. I do not know for sure if fixing this will make it all work, but it certainly wont work with this issue.

getArticles is a function that returns nothing and yet you call it as if it is a function that returns something. Now even if you would add a return statement to this function, it will still return undefined because calls to the database happen asynchronously. This means that the function will return before the data was actually retrieved from the db. This function would at the very least require a callback to be passed in, or else you can look in to the mysql-promise library and use that instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.