Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

react native - how to implement redux middleware to refresh JWT tokens?

I am implementing a React Native Redux app that uses JWT tokens for authentication. There are many actions that require valid JWT tokens that are dispatched simultaneously. Ideally what I want is to implement a middleware that will first check whether the JWT token is expired or near expiry, and if that is true then queue all API calls by saving them inside an array until the JWT token is refreshed. Below is my current middleware implementation, but I am stuck and would love to get help.

The problem with the below implementation is that I don't think I fully understand how to dispatch the queued actions after the token is refreshed?

Note: I am not thinking of using axios interceptors for now plus no third party library.

function refreshTokenMiddleware() {
  let actionQueue = [];
  return ({ dispatch, getState }) => next => action => {
    const {
      userReducer: { authTimestamp },
      tokenReducer: { loading }
    } = getState();
     // Get access token and refresh token from the keychain.

    if (typeof action === 'function') {
      const isTokenExpired = getDiffDays(new Date(), new Date(authTimestamp));

      if (token && refreshToken && isTokenExpired) {
        actionQueue.push(action);

        if (actionQueue.length === 1) {
          dispatch(refreshToken()).then(() => {
            // How to loop through the queued actions and dispatch them all here?
            actionQueue = [];
          });
        }
      }
    }
    return next(action);
  };
}
question from:https://stackoverflow.com/questions/65644026/how-to-implement-redux-middleware-to-refresh-jwt-tokens

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

1 Reply

0 votes
by (71.8m points)

You could use Redux Multi in this case. It enables you dispatch multiple actions at once from an array of actions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...