0

I'm trying to get all the posts from firebase and add them to an array but am getting the error:

Uncaught (in promise) TypeError: Cannot read property 'blogItems' of undefined

here is the script:

  export default {
    data(){
      return{
        blogItems: []
      }
    },
    mounted(){
      this.getPosts();
    },
    methods:{

      getPosts(){

        database.collection('blog').doc('yP6aYXvisFbTsqtQ3MEfuyz6xYE3').collection('posts').get().then(snapshot =>{

          const posts = snapshot.docs.map(doc => doc.data())
          posts.forEach(function(post){
            this.blogItems.push(post.content)
          })
        })
        
      },

    }

  }
Marko
  • 535
  • 2
  • 6
  • 26

1 Answers1

1

In your case the this in this.blogItems to posts.

You have two ways to resolve this

  1. store the this to a variable and use it

    getPosts(){
      let tis = this;
    
     database.collection('blog').doc('yP6aYXvisFbTsqtQ3MEfuyz6xYE3').collection('posts').get().then(snapshot =>{
    
       const posts = snapshot.docs.map(doc => doc.data())
       posts.forEach(function(post){
         tis.blogItems.push(post.content)
       })
     })
    
     },
    

  1. Using the Arrow functions

     getPosts(){
    
     database.collection('blog').doc('yP6aYXvisFbTsqtQ3MEfuyz6xYE3').collection('posts').get().then(snapshot =>{
    
       const posts = snapshot.docs.map(doc => doc.data())
       posts.forEach((post) => {
         this.blogItems.push(post.content)
       })
     })
    
     },
    
Sowmyadhar Gourishetty
  • 1,843
  • 1
  • 8
  • 15