Implementing a Loading Middleware with Redux-Saga

Shows how to toggle global loading masks at the saga layer, wrap effects with middleware, and avoid repetitive spinner code.

Apr 15, 2020 · 1 min read · 202 Words · -Views -Comments · Programming
React 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Some flows in our project take time. For a single API call, interceptors can toggle a loading spinner. But when an effect chains multiple requests and additional logic, API-level loading flickers on and off. We need loading control at the saga level.

Goal

When an action handled by a saga fires, show a loading mask. When the effect finishes, hide it.

Implementation

import { call, put } from 'redux-saga/effects';
import * as is from '@redux-saga/is';

const LOADING_BLACKLIST = [UserActionTypes.GET_USERS];

function isForkEffect(eff) {
  return is.effect(eff) && eff.type === 'FORK';
}

function loading(sagaFn) {
  return function* (action) {
    function* loadingWrapper() {
      yield put(loadingStatusAction(true));
      yield call(sagaFn, action);
      yield put(loadingStatusAction(false));
    }

    if (LOADING_BLACKLIST.includes(action.type)) {
      return yield call(sagaFn, action);
    } else {
      // @ts-ignore
      return yield call(loadingWrapper, action);
    }
  };
}

const effectMiddleware = (next) => (eff) => {
  if (isForkEffect(eff)) {
    eff.payload.args[1] = safe(eff.payload.args[1]);
    eff.payload.args[1] = loading(eff.payload.args[1]);
  }
  return next(eff);
};

export const sagaMiddleware = createSagaMiddleware({
  effectMiddlewares: [effectMiddleware],
  onError: sagaEffectUnhandled
});

Notes

  1. loading is a higher-order saga. It wraps the original saga function with “loading on/off” dispatches.
  2. Since saga functions are generators, the wrapper continues to return a generator.

Final Thoughts

Without middleware you’d repeat spinner toggling everywhere, violating DRY. This approach keeps the codebase clean.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover