I want to my middleware to wait until a specific action has fully completed

I am trying to implement refresh token functionality in my reactjs app.
I created a middleware, apart from my saga middleware, to intercept each dipatched action.
This middleware checks the expiry time of access token. If it is expired, then it dispatches a call to refresh this token and then continues where it left off.
This is my middleware,

const jwtSaga = (store) => (next) => (action) => {
  const refreshTokenError = (state) => state.refreshTokenError;
  const token = localStorage.getItem(pamAccessToken);
  if (action.type == "REFRESH_TOKEN_FAILURE") {
    PopUp({
      description:
        "Your Session has expired, please login to pick up where you left off",
      type: "error",
      styleClass: "error-outer",
    });
    store.dispatch(signOutStart());
  }
  else if (
    action.type != "SIGN_OUT_START" &&
    action.type != "SIGN_OUT_SUCCESS" &&
    action.type != "REFRESH_TOKEN_START" &&
    action.type != "REFRESH_TOKEN_SUCCESS" &&
    action.type != "LOGIN_SUCCESS" &&
    action.type != "LOGIN_FAILURE" &&
    action.type != "LOGIN_START"
  ) {
    if (token && jwt_decode(token).exp <= Date.now() / 1000) {
      store.dispatch(refreshTokenStart());
      // take(refreshTokenStart());
    } else {
      next(action);
    }
  } else {
    next(action);
  }
};

It works as I want it to, but my issue right now is, that while the store.dispatch(refreshTokenStart());
is ongoing,
there is another thread running for the next action and that too falls within this condition.
Hence, if there are multiple calls to back end, this refresh token end point is hit for each of that call.
I want to stop other threads while this refresh token action completes, but only for this action.
I can’t seem to understand much.
I looked into the documentation, found take but I was not able to use it properly nor was I completely sure that it was the right approach.
Any help(and code improvement suggestions) would be appreciated.

Source: Ask Javascript Questions

LEAVE A COMMENT