✨ Another approach to render asynchronous redux app on the server

Birkir Gudjonsson
2 min readJun 16, 2016

I’m Birkir Gudjonsson, software engineer currently living in Reykjavík, Iceland and working for UENO. (a digital agency based in SF). We craft web-sites and apps for some pretty big names, using all the awesome tools and frameworks that the JS Gods have given us.

So most people render their React app only on the client while others also render on the server, often called Universal, which most of our clients usually want.

The easiest server render approach is to manually fetch the data needed and inject it into the state before rendering. Dan Abramov demonstrates how this can be achieved in the redux docs 📘.

The problem here is that your state becomes inconsistent between the client and the server because the redux actions don’t handle adding data to the state like they do on the client.

Other, more dynamic approach is to use the react-router’s “match” method to get a component tree from the router, parse it and find components that contain a special method that dispatches an async action, waits for them to resolve and then renders.

This method is limited to route components only, and all later actions that might happen as an result won’t 🔥 .

OK, now what…

After chasing the same problem in another project involving rethinkdb (which is pretty async, right? 😎), I went in similar direction, only with these principles in mind.

  1. We need to handle all connected components, not just route components.
  2. The redux actions can flow pretty far before we want to render.
  3. Render before action flow completes within given timeframe.

Add this tiny reducer function so we now know which action type is being dispatched in all subscription methods. 🐜

Next, you may need to rename some of your action types, because most of the magic 🎩🐇 lies in this part.

By appending “_AWAIT” to a action constant, we can tell that this action will be a promise, that will not execute imminently. When this particular action will complete, we dispatch similarly named action, but instead of the AWAIT suffix we use SUCCESS 👍 or FAILED 👎.

So if I stick to the naming convention, I can write a listener function that monitors these kinds of actions, and makes decisions about waiting or rendering.

Please checkout the github demo below which I based on this approach and give it a shot 🔫, also let me know if you have any comments or better solutions to the problem.

https://github.com/birkir/universal-redux-demo

--

--