Understanding Redux Middleware

Middleware is created by composing functionality that wraps separate cross-cutting concerns which are not part of your main execution task.

 

In the case of Redux middleware the main execution task is the store’s dispatch function. The dispatch function is responsible for sending actions to one or many reducer functions for state changes. The composed specialised functions around the original dispatch method creates the new middleware capable dispatch method.

 

Redux Middleware

Middleware provides a way to interact with actions that have been dispatched to the store before they reach the store’s reducer. Examples of different uses for middleware include logging actions, reporting errors, making asynchronous requests, and dispatching new actions.

 

Redux Dispatch Function

A Store in Redux have a dispatch function which is only concerned with the main execution task you are interested in. You dispatch actions to your reducer functions to update state of the application. Redux reducer functions take a state and action parameter and return a new resultant state:

reducer:: state -> action -> state

You might dispatch an action that simply sends a message to remove an item in a list which could look like this:

{type: types.DELETE_ITEM, id: 1}

 

Redux Middleware

 

Redux middleware is designed by creating functions that can be composed together before the main dispatch method is invoked. Let’s start by creating a very simple logger middleware function that can echo the state of your application before and after running your main dispatch function. Redux middleware functions have this signature:

middleware:: next -> action -> retVal

 

Asynchronous Middleware

Once you get comfortable with the basics of Redux middleware you will likely want to work with asynchronous actions that involve some sort of asynchronous execution. In particular look at redux-thunk for more details. Let’s say you have an action creator that has some async functionality to get stock quote information:

function fetchQuote(symbol) {

   requestQuote(symbol);

   return fetch(`http://www.google.com/finance/info?q=${symbol}`)

      .then(req => req.json())

      .then(json => showCurrentQuote(symbol, json));

  }