0

I am making a react app and I am stuck on the islogged in part.

I have a fairly simple privateRoute system which is set up like so.

<Route {...rest} render={props => (
    isLogin() ?
        <Component {...props} />
    : <Redirect to="/" />
)} />

The problem starts when trying to return isLogin()

I connect to my api with a token i obtain from the login screen and i am getting back the correct status code however no matter what I do it never returns true or false. I get the console.log printed but thats as far as it goes.

    import axios from "../api/axios";

export const isLogin = () => {
    axios({
        method: "POST",
        url: "/userinfo",
        headers: { Authorization: `Bearer ${token}` }
      }).then(res => {
          if(res.status === 200){
              console.log("connected")
              return true
          }else{
              return false
          }
      }).catch(() => {
          return false
      });  
    }

Honestly stumped on how to get around this as I am fairly new.

Matt
  • 791
  • 4
  • 13
  • This is one of the most common types of questions on Stackoverflow. [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Andy Ray Aug 11 '21 at 16:35
  • @Bravo Well it is being called in my ```isLogin()``` part of the route. I know that works as I can return true or false instead of using axios and it works – Matt Aug 11 '21 at 16:38
  • @AndyRay I have seen this but I honestly do not understand the answer :( Just gone straight over my head, would you be able to guide me or show me on my code? – Matt Aug 11 '21 at 16:40
  • @Bravo Yes there is? Top part which has ``` – Matt Aug 11 '21 at 16:41
  • You need to wait for the promise to complete in your component, and store the result in state, and render based off the state, or you need to do the same thing in a parent component, and don't render the child component until the promise has finished. @Bravo react has nothing to do with promises, it's just javascript – Andy Ray Aug 11 '21 at 16:42
  • @AndyRay I know i could call the api in the privateRoute component and then use a state from there but states have limitations such as new tabs ect so seems so messy if thats what you mean – Matt Aug 11 '21 at 16:46

0 Answers0