0

I'm calling a function that uses a person's user name to find the current User in my database. When I log the current user in my function, it works fine, but after that it says it null or undefined whenever i try to access it.

In my mounted:

mounted() {
    this.getCurrentUser(this.currentUserName);
    console.log(this.currentUser)

  }

In my getCurrentUser():

getCurrentUser(currentUserName){
        UserDataService.getCurrentUser(currentUserName)
            .then(response => {
               this.currentUser = response.data;
               console.log(this.currentUser);
            })
              .catch(e => {
              console.log(e);
            });
    }

In my UserDataService:

getCurrentUser(userName){
        return http.get("/users?userName="+userName);
     }

This is when it is logged inside of the getCurrentUser function

Otherwise, it is null after i LOG it in mounted().

  • See also https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Estus Flask Apr 14 '20 at 07:44
  • 1
    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) – bill.gates Apr 14 '20 at 07:44

1 Answers1

2

You make an async call. The result of getCurrentUser is not available right away.

The log in the method waits for that, but in mounted you don't wait.

You can make mounted async and wait for the result, but you'll have an empty component in the mean time.

async mounted() {
    await this.getCurrentUser(this.currentUserName);
    console.log(this.currentUser)
}

and return the promise from getCurrentUser

getCurrentUser(currentUserName){
   return UserDataService.getCurrentUser(currentUserName)
Radu Diță
  • 13,476
  • 2
  • 30
  • 34