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

怎甘沉沦 提交于 2021-02-05 11:21:10

问题


I read a collection about book checkout from firestore in create().

The data is store in checkout array that declared in data().

export default {
  name: "checkout-history",
  data() {
    return {
      checkout: []
      ]
    };
  },
  created() {
    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
      }
      ......

When I run console.log(this.checkout);, console show this:

However, I cannot iterate it, the console show this.checkout.length is 0

I also tried to use Object.keys but no luck.

Object.keys(this.checkout).forEach(key => {
     const keys = this.checkout[key];
     console.log(keys);
});

I really don't know what to do anymore.

I read many answers online and tried most of them, but none of them work.


回答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:

  • How to get data from firestore DB in outside of onSnapshot

  • Why are Firebase APIs asynchronous?




回答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.



来源:https://stackoverflow.com/questions/57147692/array-of-json-object-is-not-empty-but-cannot-iterate-with-foreach-show-zero-len

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!