Saad Ali
Saad Ali

Reputation: 23

Assigining Data from firestore get to a variable

Im trying to assign variables to their respected value from the firestore database using the get doc function, I've noticed it does not assign or update the values what so ever.

I've tried to work with async and awaits but cannot seem to make it work.

getFromDatabase(nameOfCollection,nameOfDocument){

    const db = firebase.firestore();
    var docRef = db.collection(nameOfCollection).doc(nameOfDocument);
    docRef.get().then(function(doc) {
        if (doc.exists) {

         outvariable = doc.data().anyfield; // THIS IS WHAT I WANT
         console.log(" Document data:", doc.data());
        } else {
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

  }

im expecting outvariable = doc.data().anyfield

Upvotes: 2

Views: 4583

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Most likely you're confused by the fact that data is loaded from Firestore asynchronously. It's not so much that the data isn't assigned to the values, because it really is. It just happens at a different time than you expect.

It's easiest to see this by adding some simple logging statements around the code that loads data:

const db = firebase.firestore();
var docRef = db.collection(nameOfCollection).doc(nameOfDocument);
console.log("Before starting to load data");
docRef.get().then(function(doc) {
  console.log("Got data";
});
console.log("After starting to load data");

When you run this code, the output is:

Before starting to load data

After starting to load data

Got data

This is probably not what you expected, but it's actually completely correct. The data is loaded from Firestore asynchronously (since it may take some time), and instead of waiting, the main code continues. Then when the data is available, your callback function is called with that data.

This means that any code that requires the data from the database must be inside the callback, or be called from there. So the console.log(" Document data:", doc.data()) in your original code should work fine. But a similar console.log outside of the callback won't work, because it runs before the data is available.

This is an extremely common source of confusion for developers new to this type of API. But since most modern web/cloud APIs, and many other APIs, are asynchronous, it's best to learn how to work with them quickly. For that, I recommend reading:

Upvotes: 2

sllopis
sllopis

Reputation: 2368

The data can be extracted with .data() or .get() to get a specific field.

For example: doc.get(anyfield);

More info can be found on the official documentation.

Upvotes: 1

Related Questions