Write your own custom asyncDispatch middleware

ibrahimshamma99 profile image Ibrahim Abushammah ・1 min read

As the default dispatch provided by react-redux library is a synchronous call I needed to make calls to the server where I don't want to make changes to the structure to the code base
Redux docs suggests writing your own custom middleware instead and it turns out being super easy


const asyncDispatchMiddleware = (store) => (next) => (action) => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach((a) => store.dispatch(a)); // flush queue
    actionQueue = [];

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {

  const actionWithAsyncDispatch = Object.assign({}, action, { asyncDispatch });

  syncActivityFinished = true;

export default asyncDispatchMiddleware;

when writing middleware Store, next state and action are your parameters

Then bind this middleware into your collection of middleware using


method provided by Redux

import { createStore } from "redux";
import { applyMiddleware } from "redux";
import asyncDispatchMiddleware from './asyncDispatch';
import rootReducer from "./Reducer"; 
//Your reducers either root or combined version

const store = createStore(rootReducer,
    // your other middlewares ex thunkMiddleware orloggerMiddleware

export default store;

Custom middlewares are very useful because of ease of extensibility
Good luck

Posted on Mar 11 by:

ibrahimshamma99 profile

Ibrahim Abushammah


ReactJs & NodeJs developer. Self educated and very enthusiastic about programming.


markdown guide