2

I'm playing with firebase right now, and I want to get display posts from the database. I've got an array of objects, but I don't know how to get the data into the array. This is my code:

import * as firebase from "firebase/app";
import db from "@/plugins/firebase";
export default {
  data() {
    return {
      posts: []
    };
  },
  methods: {
    get() {
      db.collection("posts")
        .get()
        .then(snapshot => {
          snapshot.forEach(doc => {
            this.posts = doc.data();
            console.log(this.posts);
          });
        })
        .catch(err => {
          console.log("Error getting documents", err);
        });
    }
  }
};
2
  • What's the problem with the code you shared? Commented Oct 30, 2019 at 11:11
  • I think you don't need forEach the snapshot.data() should be an array of objects Commented Oct 30, 2019 at 11:13

3 Answers 3

1

Figured it out, turns out I had to create a new object and then use the spread operator.

This is the working code:

    get() {
      db.collection("posts")
        .get()
        .then(snapshot => {
          let items;
          snapshot.forEach(doc => {
            this.posts.push({
              ...doc.data()
            });
          });
        })
        .catch(err => {
          console.log("Error getting documents", err);
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Try using

.then(snapshot => {
          snapshot.forEach(doc => {
            this.posts.push(doc.data());
          });

All you need is to use push() method so that the data coming from Firebase will get into the array defined above.

3 Comments

I have tried this, but this.posts is now an observer. When I loop through the posts it does display the correct number of posts, but doesn't display the data, like post title etc. console.log(this.posts) returns this -> imgur.com/a/pNnl0eN
Maybe with the use of map() operator the data would get transformed into JSON object and then using the subcsribe() method you can display the object data easily.
I used JSON.stringify(doc.data()) If I try using .map() it says snapsot.map() is not a function
0

If @shaykoo is getting the idea of your question right then you must use reactive variation of push() method like this:

.then(snapshot => {
          snapshot.forEach((doc,i)=> {
            this.$set(this.posts, i, doc.data());
          });

1 Comment

Any errors in console? What is console.log(snapshot.data()) output?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.