acidjazz / tv-toast

Programmatic toasts for Nuxt.js powered by Tailwind CSS
MIT License
116 stars 11 forks source link

Call from promise #11

Open flakerimi opened 4 years ago

flakerimi commented 4 years ago

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

acidjazz commented 4 years ago

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

flakerimi commented 4 years ago

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 })