Redux Middleware

Merna Zakaria
6 min readSep 12, 2019

We have a series of articles about react and how it works with redux:
-Redux without React
-React cooperating with Redux
-Integrating React with Redux
-Redux Middleware
-Redux-From

Redux Problem:

By default actions in Redux are dispatched synchronously,

But the front-end world is not synchronous.

which is a problem for any non-trivial app that needs to communicate with an external API and wait for an API response, or cancel an ongoing action, suddenly your application can’t be composed anymore of just the synchronous functions. Synchronous Redux reducer ends up not being enough, because many effects of UI actions are asynchronous, i.e.:

· Actions such as “filtering search results” and “retrieving API response” takes time and can’t be dispatched immediately.

· Actions such as “cancel the ongoing request when the new one is done” need to rely on other actions (not the reducer’s state).

Before taking about Redux-Middleware, I want to tell you how Javascript solves asynchronous problem through Event Loop

You’ve probably heard that JavaScript is a single-threaded language. You may have even heard the terms Call Stack and Event Queue. Most people know that the Event Loop is what allows JavaScript to use callbacks and promises.lets see how JavaScript code is actually executed.

The Call Stack:

JavaScript has a single call stack in which it keeps track of what function we’re currently executing and what function is to be executed after that. But first — what’s a stack? A stack is an array-like data structure but with some limitations — you can only add items to the back and only remove the last item. Another example is a pile of plates — you put them on top of each other and at any time you can only remove the top one.to the back and only remove the last item. Another example is a pile of plates — you put them on top of each other and at any time you can only remove the top one.

The Event Table & Event Queue:

Every time you call a setTimeout function or you do some async operation — it is added to the Event Table. This is a data structure which knows that a certain function should be triggered after a certain event, and it does not execute functions and does not add them to the call stack on it’s own. It’s sole purpose is to keep track of events and send them to the Event Queue.

The Event Queue is a data structure similar to the stack — again you add items to the back but can only remove them from the front. It kind of stores the correct order in which the functions should be executed. It receives the function calls from the Event Table, but it needs to somehow send them to the Call Stack? This is where the Event Loop comes in.

The Event Loop:

We’ve finally reached the infamous Event Loop. This is a constantly running process that checks if the call stack is empty. Imagine it like a clock and every time it ticks it looks at the Call Stack and if it is empty it looks into the Event Queue. If there is something in the event queue that is waiting it is moved to the call stack. If not, then nothing happens.

Event table => event queue => Event loop => Call stack

One of the benefits of Redux is that it makes state changes predictable and transparent. Every time an action is dispatched, the new state is computed and saved. The state cannot change by itself, it can only change as a consequence of a specific action.

Middleware Concept:

Thankfully though, Redux allows for middleware is some code you can put between an action being dispatched and the action reaching the reducers. Middleware extend the store’s abilities, and let you write async logic that interacts with the store, through allows you to have special action creators (without middleware action creator are functions that return an action object which is passed to the action dispatcher) — which instead of returning an action object, return a function that dispatches actions asynchronously over time.

There are two very popular middleware libraries that allow for side effects and asynchronous actions: Redux Thunkand Redux Saga. In this post we’ll introduce the former: Redux Thunk.

Redux Thunk:

what is a thunk?

A thunk is a function that acts as a wrapper in that it wraps an expression to delay its evaluation. For example, in the below code, the foo function acts as a thunk as it delays the calculation of the mathematical expression, 1 + 2.

The thunk can then be used to delay the dispatch of an action until the fulfillment of an asynchronous line of code (e.g., an axios request to receive data).

How do Redux Thunk work ?!

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed.

  1. Firstly install redux-thunk library using command

$ npm install — save redux-thunk

2. Second step create action

Below (source code of redux-thunk library) is a process of Redux-Thunk:

Check what the incoming action is:

  • If it is a regular action object, Redux-Thunk does not do anything and the action object is processed by the store’s reducer
  • If the action is a function, Redux-Thunk invokes it and passes it the store’s dispatch and getState methods and any extra arguments (e.g., axios)
  • After the function runs, the thunk then dispatches the action, which will then update the state accordingly

There are two parts to Redux-Thunk:

  • A thunk creator, which is an action creator that returns a thunk (a.k.a. asynchronous action creators)
  • The thunk itself, which is the function that is returned from the thunk creator and accepts dispatch and setState as arguments

3. Create the rootReducer and postReducer.

4.Configure the redux Store

Summary:

Without middleware, Redux store only supports synchronous data flow. This is what you get by default with createStore().

You may enhance createStore() with applyMiddleware(). It is not required, but it lets you express asynchronous actions in a convenient way.

Asynchronous middleware like redux-thunk wraps the store’s dispatch() method and allows you to dispatch something other than actions, for example, functions or Promises. Any middleware you use can then intercept anything you dispatch, and in turn, can pass actions to the next middleware in the chain.

References:

https://github.com/reduxjs/redux-thunk

https://alligator.io/redux/redux-thunk/

https://medium.com/better-programming/handling-asynchronous-actions-in-redux-86724ed87c6c

https://redux.js.org/advanced/middleware

https://redux.js.org/advanced/async-flow

https://medium.com/@shoshanarosenfield/redux-thunk-vs-redux-saga-93fe82878b2d

https://hackernoon.com/understanding-js-the-event-loop-959beae3ac40

https://flaviocopes.com/javascript-event-loop/

--

--