1

Result undefined when I try to get value from firestore and put to a variable, but works in console.

My code:

this.db.collection('Users').doc(uid).get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      this.db.collection('Users').doc(uid)
        .onSnapshot((doc) => {
          console.log(doc.data()); //working
          perfil = doc.data(); //not working
        });
    }
  });

console.log(perfil); //not working. Display undefined
etarhan
  • 4,138
  • 2
  • 15
  • 29

1 Answers1

3

The data is loaded from Cloud Firestore asynchronously. Because this may take some time, the code after the callback immediately continues. Then when the data is available, Firestore calls your onSnapshot callback.

It's easiest to see what's happening by adding a few log statements:

console.log('Before adding listener');
this.db.collection('Users').doc(uid).get()
.then((docSnapshot) =>{
  console.log('Got data');
});
console.log('After adding listener');

When you run this code, it prints:

Before adding listener

After adding listener

Got data

This is probably not the order you expected. But it explains perfectly why your console.log(perfil) prints undefined: the data hasn't been loaded yet!

Because of this, all code that needs access to the data needs to be inside the onSnapshot callback. For example:

this.db.collection('Users').doc(uid).get()
.then((docSnapshot) =>{
  if (docSnapshot.exists) {
    this.db.collection('Users').doc(uid)
    .onSnapshot((doc) => {
        console.log(doc.data());
        perfil = doc.data();
        console.log(perfil);
    });
  }
});

For more on this, see:

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807