I am trying to make the server work with asynchronous calls. My problem is that the data does not load before rendering.
My code (also available on github: https://github.com/tomekbuszewski/server-rendering )
server.js
require('babel-register');
import express from 'express';
import path from 'path';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { getState } from 'redux';
import { match, RouterContext } from 'react-router'
import routes from './app/routes';
import store from './app/store';
const app = express();
const port = 666;
app.get('/', (req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (renderProps) {
console.log(renderProps.components);
res.send(renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
))
} else {
console.log('err')
}
});
});
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, 'data')));
app.listen(port);
console.log(`localhost:${port}`);
routes.js
import React from 'react';
import { Router, Route, browserHistory } from 'react-router';
import App from './Components/App';
const routes = (
<Router history={browserHistory}>
<Route path="/" component={App} />
</Router>
);
export default routes;
The App component has a fetch function:
const fetch = (dispatch) => {
const endpoint = '/data/index.json';
axios.get(endpoint).then((res) => {
Array.prototype.forEach.call(res.data, d => {
const payload = {
id: d.id,
title: d.title
};
dispatch({type: 'ADD_CONTENT', payload});
});
});
};
which dispatches the ADD_CONTENT action:
case 'ADD_CONTENT':
return { ...state, data: [...state.data, action.payload] };
Everything works perfectly on the client side.