I want to log user out based on the expiration of the token. I know there's something wrong with the Axios call, but I'm not sure what is wrong. Additionally, it seems to be logging out user fine manually but it still catches an error.
actions.js
:
export const logoutUser = (history) => ({
type: LOGOUT_USER,
payload: { history },
});
store.js
:
export const checkTokenExpiration = (next) => (action) => {
const token =
JSON.parse(localStorage.getItem('user')) &&
// eslint-disable-next-line dot-notation
JSON.parse(localStorage.getItem('user'))['token'];
if (jwtDecode(token).exp < Date.now() / 1000) {
next(action);
localStorage.clear();
}
next(action);
};
const logoutAsync = async (history) => {
await axios
.logoutUser()
.checkTokenExpiration.then((user) => user)
.catch((error) => error);
console.log();
history.push(adminRoot);
};
And this is the error message:
axios__WEBPACK_IMPORTED_MODULE_3___default.a.logoutUser is not a function
The above error occurred in task logout created by takeEvery(LOGOUT_USER, logout) created by watchLogoutUser created by rootSaga created by rootSaga
so it turns out, i've been doing the check at the wrong place.
found out with some help that i could check under another function and here are the codes:
const ProtectedRoute = ({
component: Component,
roles = undefined,
...rest
}) => {
function isAuthActive() {
const user = JSON.parse(localStorage.getItem('User'));
const expiryTime = new Date(user?.expiration * 1000).toLocaleString(
'en-sg'
);
const currentTime = new Date().toLocaleString('en-sg');
if (expiryTime < currentTime) {
setCurrentUser();
localStorage.clear();
return <Redirect to="/login" />;
}
return true;
}
};
basically just checking current time against the expiry time given by the token. the rest are set in the backend server.