denisftw
denisftw

Reputation: 3

Initial browser re-rendering when fetching data asynchronously

I'm trying to build a React app/site that uses "react-router", "redux" and server-side rendering and I don't quite understand how to deal with the initial rendering in the browser.

On the server side, I can take a JSON object, pass it to the state and then map state to props - all synchronously - and finally render the component using already initialized props.

const routes = <Router>
<Route path='/' component={ViewComposite} 
  onEnter={ ({params}) => { store.dispatch(setViewProps(props)); }} />
<Route path='/admin' component={AdminComposite} 
  onEnter={ ({params}) => { store.dispatch(setAdminProps(props)); }} />
</Router>;

However, when the browser comes into play, I need to fetch data via AJAX request - asynchronously:

window.onload = function() {
const store = createStore(viewPropsReducer);

ReactDOM.render(
    <Provider store={store} >
        <Router history={browserHistory} >
            <Route path="/" component={ViewComposite} 
 onEnter={ ({params}) => {store.dispatch(fetchViewData()); }} />
            <Route path='/admin' component={AdminComposite} 
 onEnter={ ({params}) => {store.dispatch(fetchAdminData()); }} />
        </Router>
    </Provider>,
    document.getElementById('viewMount')
);}

As a result, the rendering fails due to undefined props. Is there a way to work around this - maybe postpone browser rendering until the data is fetched?

Upvotes: 0

Views: 114

Answers (1)

rallrall
rallrall

Reputation: 4770

You could add the json payload to the server rendered html.

<script> 
    window.payload = <json>
 </script>

If your state is serializable, I guess you could just put the state there instead, and pass it as initialState when creating the store.

createStore(reducer, window.initialState);

Upvotes: 2

Related Questions