Search code examples
reactjsreduxreact-reduxredux-middleware

dispatch async function in custom middleware in redux


I am trying to create a custom middleware which dispatches logout action (async function) based on some condition in redux. As soon as action is dispatched, it throws error RangeError: Maximum call stack size exceeded

store.js:

const handleAction = (store) => (next) => (action) => {
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (token && userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};

export function configureStore(initState = {}) {
  const store = createStore(
    rootReducer,
    initState,
    composeEnhancers(applyMiddleware(thunk,handleAction))
  );
  return store;
}

What am I doing wrong? Thanks in advance


Solution

  • Prevent the logoutAction() from causing the middleware to dispatch logoutAction() and so on...

    if(action.type === 'your logoutAction type') return next(action);
    

    Example:

    const handleAction = (store) => (next) => (action) => {
    
      if(action.type === 'your logoutAction type') return next(action);
      
      const token = loadState(TOKEN);
      const { userAccount } = store.getState();
      if (token && userAccount.email) {
        const decodedJwt = jwt_decode(token);
        if (decodedJwt.exp < dayjs().unix()) {
          store.dispatch(logoutAction());
        }
      }
      return next(action);
    };
    

    You can also combine it with your existing condition:

    const handleAction = (store) => (next) => (action) => {     
      const token = loadState(TOKEN);
      const { userAccount } = store.getState();
      if (action.type !== 'your logoutAction type' && 
          token && 
          userAccount.email) {
        const decodedJwt = jwt_decode(token);
        if (decodedJwt.exp < dayjs().unix()) {
          store.dispatch(logoutAction());
        }
      }
      return next(action);
    };