Creating a Custom Middleware with Redux

You might have used redux with react, as it is a widespread practice. Many people use redux-saga or redux-thunk for async actions as middlewares. Redux allows you to create your custom middleware as per your requirement. A middleware can be added in between dispatch and reducers so that we can alter the actions or can dispatch other actions (for async actions).

This is done with a function returning function. So, let’s first understand about function returning function.

It is simple and can be done as follows -

function example(a){
    return function(b) {
        return a + b;
    }
}

We can write above in ES6 as

const example = a => b => a + b; 

The above example works when we call

example(5)(6)  // output 11

Now let’s create a middleware and apply it to the redux store.

How To Create

To create a middleware, the first function takes store (i.e. redux store) as its parameter. The function that it returns is called when the middleware is done with the assigned task and sends the action to the reducer. Here, the significance of next is that redux composes the middlewares to reference the next one. It is generally not required; however, it is helpful if you don’t want to stop dispatching further actions.

Then, the action that is currently dispatched can be given as

const customMiddleware = store => next => action => {
    ...
}

The store provides with methods getState() and dispatch(), which are helpful for getting the current state of redux and to dispatch actions from the middleware, respectively.

A simple example of a custom middleware can be given as follows -

const customMiddleWare = store => next => action => {
    console.log("Current Action : ", action);
    next(action);
}

Here, store is the redux store. The next function is called when middleware has done the job to send the action to a reducer or the next middleware, and the action is currently dispatched action.

How to Apply

To connect your middleware to redux, we use applyMiddleware() function provided by redux

import { createStore, applyMiddleware } from 'redux';

const store = createStore(reducer, 
           applyMiddleware(customMiddleWare)
    );

Now, we can log all actions of the user with the help of _redux-logger, o_r we can have multiple middlewares of our own different events occurring on the browser. As we have access to the store, we can use store functions like store.getState() and store.dispatch(). 

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype