Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

reactjs - 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

question from:https://stackoverflow.com/questions/66064590/dispatch-async-function-in-custom-middleware-in-redux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...