Search code examples
javascriptajaxexpressreactjsflux

React server-side rendering AJAX setState() - document is not defined


Without the response from the AJAX request, I will have nothing to display to the user i.e. I store everything in the database. My component GenericPage.jsx:

export default class GenericPage extends React.Component {
componentWillMount() {
        if (this.store && this.onStoreUpdated) this.store.addChangeListener(this.onStoreUpdated);
        if (!this.state.page && this.state.pageId) {
            this.fetchData();
        }
    }
onPageStoreUpdated() {
        console.info('onPageStoreUpdated');
        var page = PageStore.getCurrentObject();
        this.setState({page: page, loaded: true}); // the error goes away if I comment this out
    }
    render() {
        ...
    }
}

My Express JS server code:

server.get('*', function (req, res) {
        res.header("Access-Control-Allow-Origin", "*");
        match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
            if (error) {
                res.send(500, error.message)
            } else if (redirectLocation) {
                res.redirect(302, redirectLocation.pathname + redirectLocation.search)
            } else if (renderProps) {
                let htmlStr = React.renderToString(<RoutingContext {...renderProps} />);
                res.header("Access-Control-Allow-Origin", "*");
                res.render('layout', { reactHtml: htmlStr });
            } else {
                console.log('not found')
                res.send(404, 'Not found')
            }
        })
    });

Full stack trace:

/Users/eric/af/frontend_app/node_modules/react/lib/getActiveElement.js:23
    return document.body;
           ^
ReferenceError: document is not defined
    at getActiveElement (/Users/eric/af/frontend_app/node_modules/react/lib/getActiveElement.js:23:12)
    at ReactReconcileTransaction.ReactInputSelection.getSelectionInformation (/Users/eric/af/frontend_app/node_modules/react/lib/ReactInputSelection.js:40:23)
    at ReactReconcileTransaction.Mixin.initializeAll (/Users/eric/af/frontend_app/node_modules/react/lib/Transaction.js:168:30)
    at ReactReconcileTransaction.Mixin.perform (/Users/eric/af/frontend_app/node_modules/react/lib/Transaction.js:133:12)
    at ReactUpdatesFlushTransaction.Mixin.perform (/Users/eric/af/frontend_app/node_modules/react/lib/Transaction.js:134:20)
    at ReactUpdatesFlushTransaction.assign.perform (/Users/eric/af/frontend_app/node_modules/react/lib/ReactUpdates.js:95:38)
    at Object.flushBatchedUpdates (/Users/eric/af/frontend_app/node_modules/react/lib/ReactUpdates.js:175:19)
    at Object.wrapper [as flushBatchedUpdates] (/Users/eric/af/frontend_app/node_modules/react/lib/ReactPerf.js:70:21)
    at ReactDefaultBatchingStrategyTransaction.Mixin.closeAll (/Users/eric/af/frontend_app/node_modules/react/lib/Transaction.js:207:25)
    at ReactDefaultBatchingStrategyTransaction.Mixin.perform (/Users/eric/af/frontend_app/node_modules/react/lib/Transaction.js:148:16)

I'm using react 0.13.3 and react-router 1.0.0


Solution

  • Turns out it was not possible to achieve using React component on server side.
    So, I moved the AJAX calls to componentDidMount in my React components so that they don't affect the server side.
    The data that I need to get on the server side, I get them in my server side Node JS code, outside of any React component, before I render React components:

    server.get('*', function (req, res) {
            res.header("Access-Control-Allow-Origin", "*");
            match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
                if (renderProps) {
                    someAsyncHttpRequest(someUrl)
                        .onSuccess((response) => {
                             page = response.body;
                             renderProps.params.page = page;
    
                             Dispatcher.dispatch({
                                  actionType: AppAction.PAGE_FETCHED,
                                  data: page
                             });
                        });
                    let htmlStr = React.renderToString(<RoutingContext {...renderProps} />);
                    res.render('layout', { reactHtml: htmlStr });
                }
            })
        });