Search code examples
node.jsreactjssocket.iofluxisomorphic-javascript

React JS isomorphic render


ReactJS, original Flux, react-router, nodeJS, socket.io Everything is up to date.

If i'm switching off javascript in browser, only static code is being rendered.

During server side render ComponentWillMount and render methods being fired up, but not ComponentDidMount.
Even if I'm putting Flux logic into ComponentWillMount method, nothing happen: action is called, but socket.io doesn't send request to server to get data from database. Which means, no data being retrieved from database and nothing useful for search engines is being rendered. If javascript is enabled, everything works perfect.

Here the important pieces of code:

Component. Add listener and call action:

componentDidMount() {
    StoreUser.addChangeListener(this._onChange);
    Actions.getUser(this.props.params.userid)   
}

Client's action asks server for user data:

function _getUser (userid) {
  socket.emit('getUser', userid)
}

up until this place server-side rendering works, but server itself doesn't received getUser event, so nothing happens further. Again, if javascript is enabled in browser, all this works fine. Server receives this call and returns user's data.

How do i make server receive this event, return user's data and render it before sending to client? As alternative, may be there is different way to make it SEO friendly?


Solution

  • React's componentDidMount lifecycle hook is not called server-side, as stated in the docs.

    If you need to fetch data and use it server-side in the render method of a component, you need to pass this data as props during the initial render. This means, you cannot fetch it either during componentWillMount, even if the hook is called.

    To achieve what you want, you need your server-side code to:

    • determine what components will be rendered
    • dispatch the proper actions so that your store will be properly populated
    • render your components only then - as the data is available to pass to your components in an initial render

    The details on how to achieve that would of course depend on your flux implementation, the framework you use server-side, etc.