0

I have written the following code to render some posts (which are stored in a Cloud Firestore instance). I am using mithril.js.

let SummaryPostView = {
  posts: [],
  view: function () {
    let query = blogModels.postModel.getNLatest(20, "created");
    query.then(function (data) {
      this.posts = data;
      console.log("INSIDE VALUE: ");
      console.log(this.posts);
    });
    console.log("OUTSIDE VALUE: ");
    console.log(this.posts);
  }
};

When I run my code, I obtain the following console output: Console output

The value of this.posts is different outside the function to the value of this.posts inside the function. As the behaviour of this can be confusing I have also tried the following code:

let SummaryPostView = {
  posts: [],
  view: function () {
    let query = blogModels.postModel.getNLatest(20, "created");
    var x = [];
    query.then(function (data) {
      x = data;
      console.log("INSIDE VALUE: ");
      console.log(x);
    });
    console.log("OUTSIDE VALUE: ");
    console.log(x);
  }
};

The result of this code is the same: enter image description here

In response to Chris Sandvik's answer I have also tried the following code

let SummaryPostView = {
  posts: [],
  view: function () {
    let query = blogModels.postModel.getNLatest(20, "created");
    query.then(function (data) {
      this.posts = data.docs.map(function (doc) {
        let out = doc.data();
        out.id = doc.id;
        return out;
      });
      console.log("INSIDE");
      console.log(this.posts)
    });
    console.log("OUTSIDE");
    console.log(this.posts);
  }
};

This still results in the same problem: enter image description here

Teymour
  • 1,832
  • 1
  • 13
  • 34
  • All code that needs access to the data, must be inside the callback or be called from there. See https://stackoverflow.com/questions/52488087/how-to-get-data-from-firestore-db-in-outside-of-onsnapshot – Frank van Puffelen Jun 22 '19 at 02:43

1 Answers1

1

Since your output is a QuerySnapshot, you need to access your data like so:

query.then(function (data) {
  this.posts = data.docs.map(doc => {
    let out = doc.data();
    out.id = doc.id;
    return out;
  });
});

You need to access the array of documents in your QuerySnapshot using the docs property and the access their data with the .data() method.

More info here: https://firebase.google.com/docs/reference/js/firebase.firestore.QueryDocumentSnapshot.html

Chris Sandvik
  • 1,787
  • 9
  • 19