Reputation: 549
I am trying to decode the JWT token in order to check wheather is it valid or not. But I am getting the error that the decoded object is possibly 'undefined'
import jwt_decode, { JwtPayload } from "jwt-decode";
if (token) {
const decoded = jwt_decode<JwtPayload>(token || "") || null;
if (decoded) {
const currentTime = Date.now() / 1000;
if (decoded?.exp < currentTime) { //Object is possibly 'undefined'.
dispatch(logout());
localStorage.removeItem("token");
setLoading(false);
}
}
}
Upvotes: 2
Views: 1525
Reputation: 3965
decoded.exp
is possibly undefined
, so you have to check it first before comparing it to currentTime
if (decoded?.exp && decoded.exp < currentTime) { }
Upvotes: 4