Reputation: 945
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);
});
}
}
};
Upvotes: 2
Views: 2412
Reputation: 945
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);
});
}
Upvotes: 1
Reputation: 692
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());
});
Upvotes: 0
Reputation: 61
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.
Upvotes: 0