Redux Middleware

The basic idea of Redux is that you have a global application state, which gets updated by dispatching an Action through a Reducer. However, what if that isn’t enough? Fortunately, Redux has something called Middleware. Have you used Redux-Promise? If so then already used Middleware even if you don’t know it. If you look at the code of this package, its just one file – a Redux middleware!

Middleware Defined

Middleware in Redux allows us to extend our Redux Application. Middleware gets called before the dispatched action hits our reducers. In the case of redux promise, it is used to resolve the promise before hitting the reducers, which would then give our application a new state.

Redux Promise Middleware Example

Lets take a look at the problem that Redux-Promise is solving. When you make an ajax call with a promise, and include that result in your action, there is a good chance that this action hasn’t been completed yet by the time it hits the Reducer, rendering it useless.

Redux Promise is basically one file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { isFSA } from 'flux-standard-action';

function isPromise(val) {
  return val && typeof val.then === 'function';
}

export default function promiseMiddleware({ dispatch }) {
  return next => action => {
    if (!isFSA(action)) {
      return isPromise(action)
        ? action.then(dispatch)
        : next(action);
    }

    return isPromise(action.payload)
      ? action.payload.then(
          result => dispatch({ ...action, payload: result }),
          error => {
            dispatch({ ...action, payload: error, error: true });
            return Promise.reject(error);
          }
        )
      : next(action);
  };
}

The biggest thing to notice in this is that Redux Promise is basically saying “Hey is this action a promise? if it is lets run action.payload.then. You can specifically see this in promiseMiddleware. After it determines that the action contains a promise, it will process it. Assuming a successful result, it will then stuff that result in action.payload.

You will also notice the next parameter in the middleware function. All this does is take the action and move it to the next middleware if there is another one. Otherwise it will take the middleware and finally move it to the reducers. In the case of Redux Promise by the time our action hits the reducer, the Promise will automatically have been resolved, and we can work with the final data.

If you don’t know what is going on behind the scenes, it can almost seem magical. However, Redux Promise is basically one file that utilizes a powerful Redux feature called Middleware.

Other Uses of Middleware

Redux Middleware has other uses besides resolving promises. Other common uses are (but not limited to):

  • Logging
  • Crash Reporting
  • Confirmation Messages