I use react with redux and use JWT token to authentication users, JWT has short life time and I wrote a middleware to refresh token like as below:
import { refreshToken, refreshTokenFail } from '../actions/index';
const jwtTokenRefresh = ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
const timeStamp = Math.floor(Date.now() / 1000);
const expiration = getState().auth.expiration;
if (expiration && timeStamp > expiration && !getState().auth.refreshToken) {
return refreshToken(dispatch)
.then(() => {
return next(action)
}).catch(() => {
console.log('fail')
dispatch(refreshTokenFail(dispatch)).then(() =>{
window.location.href= "/login";
})
});
}
}
return next(action);
};
export default jwtTokenRefresh;
But now I want write new react app without redux and using from react context, how can I refresh token in react context?