Mathias Riedel
Mathias Riedel

Reputation: 67

console.log() displays the correct value, but when assigned it to a variable, it is undefined - Angular, firestore

I'm working on an Angular application and want to get some data from Firestore. But my function always returns undefined. When I, however, console.log() the value before returning it, it displays the correct value.

getToken(user_id) {
    this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token; //returns undefined!
      }
    });
}

Shouldn't both values be the same?

Upvotes: 1

Views: 825

Answers (2)

Ian
Ian

Reputation: 6124

It appears that you are not returning the Promise from your function - there is no return statement in the getToken function at all, so the function itself just returns undefined. The internal return statement you have will resolve the promise, which is good, but you have to handle that resolution.

If you return the promise like so:

getToken(user_id) {
    return this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
      if (doc.exists) {
        console.log(doc.data().user_token); //displays the correct user_token value
        return doc.data().user_token;
      }
    });
}

You should be able to access the user_token asynchronously when the promise resolves by doing the following:

getToken(user_id).then(user_token => {
  handle_user_token_here(user_token);
});

Note: The function as modified will return a promise. Therefore, you cannot simply the following:

let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
handle_user_token_here(user_token); // will not work.

You can do this though:

let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
user_token.then(user_token => handle_user_token_here(user_token)); // will work

Upvotes: 2

CircuitScholar
CircuitScholar

Reputation: 59

This may answer your question: Can't access object property, even though it exists. Returns undefined

"The output of console.log(anObject) is misleading; the state of the object displayed is only resolved when you expand the > in the console."

In other words, doc.data().user_token might be getting populated by an asynchronous process.

Upvotes: 0

Related Questions