I got an unexpected behavior when a user login to app. I store a jwt token in a cookie. Before logging into app,I checked whether jwt token is exists and that token is valid with backend.
Below is my code. Here is app.js.
class App extends Component {
render() {
return (
<BrowserRouter>
<Layout>
<LoginRoute></LoginRoute>
</Layout>
</BrowserRouter>
);
}
}
LoginRoute component is as below.
const LoginRoute = withRouter(({ history }) => (
isValidUser() ? (
<Switch>
<Route path="/incident-reporting" component={Home}></Route>
<Redirect path='/' to='/incident-reporting/home' />
<NotFound />
</Switch>
) : (
<Switch>
<Route path="/" exact component={Login}></Route>
<NotFound></NotFound>
</Switch>
)
))
Here is isValidUser()
const isValidUser = () => {
if (cookies.get("token")) {
let token = cookies.get("token")
axios.get("https://0.0.0.0:9094/auth/v1.0.0/user-info", {
headers: { 'Authorization': 'Bearer ' + token }
}).then(
response => {
return true;
}
).catch(
error => {
return false;
}
)
//return true
} else {
return false;
}
}
But I can't login in to app with valid token. isValidUser()
return undefined
before exucuting axios post request. How to solve this problem?