[Vuejs]-Array of JSON object is not empty but cannot iterate with foreach, show zero length

1πŸ‘

βœ…

Data is loaded from Firestore (and from most modern web APIs) asynchronously. This means that the rest of your code continues to execute after you start the query, and then when the data comes back from the database, your then() callback is called. This in turn means that all code that needs access to the data from the database, must be inside the then() callback.

db.collection("checkout")
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        const data = {
          id: doc.id, // firebase document id
          book_did: doc.data().book_did,
          borrowed_date: doc.data().borrowed_date,
          copies_did: doc.data().copies_did,
          due_date: doc.data().due_date
        };
        this.checkout.push(data); // push to array

        console.log(this.checkout)  // show data, as in the image below

        console.log(this.checkout.length)  // get 0
        console.log(Object.keys(this.checkout).length)  // get 0
      });
    });

  }
  ......

Also see:

2πŸ‘

I guess you are executing your code before the completion of the request.

If you hover over the little blue i icon, it says:

Value below was evaluated just now.

πŸ‘€Mamun

Leave a comment