I was implementing jwt authentication in ionic react with typescript so after implementing it successfully, at the en when i want to add a check in my App.tsx i am getting a typescript error
Object is of type 'unknown'
Here is my code
const App: React.FC<Idecode> = () => {
const dispatch = useDispatch();
if (localStorage.jwtToken) {
// Set auth token header auth
const token = localStorage.jwtToken;
setAuthToken(token);
// Decode token and get user info and exp
const decoded = jwt_decode(token);
console.log(decoded);
// Set user and isAuthenticated
dispatch(setCurrentUser(decoded));
// Check for expired token
const currentTime = Date.now() / 1000; // to get in milliseconds
console.log(decoded.exp, currentTime); //Here when i access exp i get an error
if (decoded.exp < currentTime) {
// Logout user
dispatch(logoutUser());
// Redirect to login
window.location.href = "./login";
}
}
return (
<IonApp>
<IonReactRouter>
<IonRouterOutlet id="menu">
<Route path="/signup" component={Signup} exact={true} />
<Route path="/" component={Home} exact={true} />
<Route path="/verify" component={Verify} exact={true} />
<Route path="/login" component={Login} exact={true} />
<Route
path="/forgot-password"
component={forgotPassword}
exact={true}
/>
<Route path="/set-password" component={setPassword} exact={true} />
</IonRouterOutlet>
</IonReactRouter>
</IonApp>
);
};
export default App;
so when i try to get "decoded.exp" ( which i get via my backend after implementing jwt ) contains data like
{id: "5f5f30cdbfd0c11d426245e5", email: "ratnabh2615@gmail.com", iat: 1600085677, exp: 1600172077}
which is stored in my localstoage in encrypted form and then i decode here
i get error of "Object is of type 'unknown'"
I think you must explicit generic type set for const decoded = jwt_decode(token);
to know type of object before it's accessed.
There are many ways. If
jwt_decode
is generic function. const decoded = jwt_decode<any| YourDefinedType>(token);const decoded : any = jwt_decode(token);
Updated following your imformation:
type JWTDeCode = {
id: string,
email: string,
iat: number,
exp: number
}
const decoded : JWTDeCode = jwt_decode(token);