0

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?

Janaka
  • 481
  • 4
  • 14
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Agney Nov 07 '19 at 12:29

2 Answers2

0

You need to wait for the isValidUser to finish. To do that, you can do this:

const LoginRoute = withRouter(async ({ history }) => (
  let isUserValid = await isValidUser()
  isUserValid ? (
    <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>
  )
))

And on the isValidUser:

const isValidUser = () => {
  if (cookies.get("token")) {
    let token = cookies.get("token")
    return 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;
  }
}
Edrian
  • 608
  • 4
  • 14
0

Your function should be asynchronous, either with ES6 async, returning promises or using callbacks. Otherwise calling the axios.get function just "falls through" and it returns the default undefined value.

fortran
  • 74,053
  • 25
  • 135
  • 175