I have a function that sends a post request to my backend, it contains the JWT token, then the backend checks if this token is correct. Unfortunately, the isAuthenticated() function only works if I return a Promise. But I want to check now in my ProtectedRoute.tsx if the token was correct. How does this work with a Promise?
isAuthenticated():
import axios from "axios"
let token = localStorage.getItem("jwt-token");
export const isAuthenticated = async (): Promise<boolean> => {
if (!token) {
return false;
} else {
let tokenCheck = false;
await axios.post("/api/users/tokencheck", { token: token }).then((res) => {
if (res.data === "Valid Token" || res.status === 200) {
tokenCheck = true
} else {
tokenCheck = false
}
})
return tokenCheck
}
}
ProtectedRoute.tsx :
import React from 'react'
import { Redirect, Route } from 'react-router-dom'
import { isAuthenticated } from "./Auth"
interface Props {
component: React.FC;
path: string;
}
const ProtectedRoute: React.FC<Props> = (props: Props) => {
return (
<React.Fragment>
{isAuthenticated()
? <Route path={props.path} exact component={props.component} />
: <Redirect to="/" />
}
</React.Fragment>
)
}
export default ProtectedRoute
backend:
export const tokenCheck = (req: Request, res: Response) => {
let { token } = req.body
jwt.verify(token!, process.env.JWTSECRET!, (err: any, decoded: any) => {
if (err) {
res.status(401).json("Invalid token");
} else {
res.status(200).json("Valid Token")
}
})
}