Search code examples
node.jsexpressreactjsisomorphic-javascript

Reactjs not loading dynamic content from database on first page load


I am fairly new to ReactJS and using NodeJS and Express to build a small SPA application. My requirement is to load data from mysql in the initial page load. The script looks something like this:

/** @jsx React.DOM */
var React = require('react');
var Request = require('request');

var HomePage = React.createClass({

    getInitialState: function() {
        return {
            name: "Batman"
        };
    },
    componentDidMount: function() {
        var obj = this;
        Request('http://ajaxtown.com/playground/data.php', function (error, response, body) {
          if (!error && response.statusCode == 200) {
            var info = JSON.parse(body);
            console.log(info[0]);
            obj.setState({
                name: info[0].firstName
            })
          }
        });

    },
    getDefaultProps: function () {
        return {
          size: 100
        }
    },

    handleClick : function() {
        console.log("Clicked");
        this.setState({
          name : "bob"
        });
    },
    render: function () {
        return (
              <h2 onClick={this.handleClick}>{this.state.name}</h2>
        );

    }
});
module.exports.HomePage = HomePage; 

This script works, but the problem is after the page load, the request is sent to the server and then the UI gets updated with the response. I am assuming this will not help SEO. Instead I want the data to be available first and then render the UI.

Secondly, I also tried to use node-mysql but because I am creating isomorphic javascript app, the credentials are visible. Not only that, browser cannot use TCP/IP, so it will still not work. So that was a lesson learnt.

If I have to create a blog application, it will be very dynamic. How will SEO work in such case ? OR is it that isomorphic javascript only implies static content ?

I am getting little mixed up with the concept. Can somebody guide me please ?


Solution

  • If you want your data to be ready before the initial rendering fetch outside:

    $.ajax({...}).success(function(res) {
         <MyView data={res} /> // render your function on success
    });
    

    Related similar post: bind(this) not working on ajax success function