Asynchronously updating redux state using middleware
Sometimes you may encounter a situation where you want to constantly update data from the server. And if WebSockets or Server-Sent Events are not available, then your only friend is polling.

The simplest example in which the latest data really matters is the messaging application in which we wanted to show the latest messages to the user without having to update the entire site. (Keep in mind that our server does not support WS \ SSE.) Therefore, we will request updates from the server every 30 seconds (short polling). To implement this functionality in the React \ Redux application - the easiest and most naive way is to set the interval in the componentDidMount method.

setInterval in Component

Here is the version with the interval, getNewMessages — a thunk action that will dispatch redux actions and update newMessages state.

But this is bad for various reasons, first of all we have to replace setInterval with setTimeout and call the next interval only after we receive a response from the server.

setTimeout in Component

Let’s rewrite it!

Now our code is better! But it still has a big problem — our update logic is in a component, in fact, this is business logic, which has nothing to do with the presentation layer. Plus updates will occur only if the NewMessages component is mounted.

initialActions in Root

So there is a problem — we need to update our data, despite what view or rote we have now! And for this we have two options. First, we can create an initialActions module where we place our update logic and call it in the root component.

This is a simplified version and there are still problems, the main of which is that we are still dependent on the presentation layer.

Middleware

Our solution here is middleware! It does not depend on the view or rote and it is connected right to the state!

This is our code, only 10 lines and without any dependencies. All it does is update messages every 500 ms from the moment the application is launched.

All we need to do now is just to connect the new middleware to the state.

Hope you enjoyed the article and find it useful, I also recommend that you look at using middleware with WebSockets:

https://gist.github.com/dmichael/9dc767fca93624df58b423d01e485402 — tip how to write WS middleware;

https://github.com/giantmachines/redux-websocket/blob/master/src/index.js — source code for Redux-WebSocket package;
['Vladislav Stepanov']
['JavaScript', 'React', 'Frontend', 'Front End Development', 'Redux']