tv-toast icon indicating copy to clipboard operation
tv-toast copied to clipboard

Call from promise

Open flakerimi opened this issue 4 years ago • 2 comments

Why I cannot call from AddPost

 created() {
  this.getData()  
},
methods: {
  getData() {
    const posts = []
    postsCollection.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        let newpost = doc.data()
        newpost.id = doc.id
        posts.push(newpost)
      })
          this.$toast.show('Keeping it simple') //works

      this.posts = posts
    })
  },
  addpost() {
      postsCollection.add({
        text: this.newpost,
        completed: false,
        id: this.posts.length,
        createdAt: new Date()
      })
      .then(function(docRef) {
        console.log("Document written with ID: ", docRef.id);
          this.$toast.show('Keeping it simple')// doesn't work

      })
      .catch(function(error) {
        console.error("Error adding document: ", error);
      });
      this.newPost = '';
    }
  }

Its driving me crazy

flakerimi avatar Nov 26 '20 23:11 flakerimi

@flakerimi did you check for what exactly is this ? are you in the nuxt context? what happens when you console.log(this.$toast)

acidjazz avatar Nov 27 '20 02:11 acidjazz

Well its undefined

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

interesting, in

postsCollection.get() .then({ here we can access 'this' console.log(this) // VueComponent{} })

postsCollection.add({...}) .then({ here we can't access 'this' console.log(this) // undefined })

flakerimi avatar Nov 27 '20 14:11 flakerimi