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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…