React with Redux and Router - Server Rendering

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.

+4
source share
1 answer
  • Your redux actions should return a promise that is executed when the store is loaded correctly with data

eg:

const fetch = (dispatch) => {
    const endpoint = '/data/index.json';

    return 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});
        });
    });
};
  1. , redux-connect, .

App

, .

import { asyncConnect } from 'redux-connect';

@asyncConnect([{
    promise: ({ store: { dispatch } }) => {
        // `fetch` is your redux action returning a promise
        return dispatch(fetch());
    }
}])
@connect(
    state => ({
        // At this point, you can access your redux data as the
        // fetch will have finished 
        data: state.myReducer.data
    })
)
export default class App extends Component {
    // ...the `data` prop here is preloaded even on the server
}

@connect , , , @asyncConnect , react-router, ()

, , redux-connect redux, promises, redux-thunk .

0

Source: https://habr.com/ru/post/1652854/


All Articles