RedEclipse
RedEclipse

Reputation: 123

Toast is undentified

I've got the information to display posts/categories depending on API results. When there's nothing to display, I want to toast a warning message.

I have following code

  async asyncData({ $axios, route, app}) {
    const [blogPost, blogCategoryPosts] = await Promise.all([
        $axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`).then(response => response.data).catch(error => {}),
        $axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`).then(response => response.data).catch(error => {}),
    ])

        if(blogPost == undefined && blogCategoryPosts == undefined) {
          this.toast.error('Error')

    }

    return {
      blogPost: blogPost,
      blogCategoryPosts: blogCategoryPosts,
      locale: app.i18n.locale
    }
  },

But it responds with Cannot read property 'toast' of undefined , why is that? I have @nuxtjs/toast enabled in my project and it works well elsewhere.

Just have added following code to same page and it worked:

    mounted() {
    // This works
    this.$toast.error('Error')
  }

Not sure how to use it with async though.

Upvotes: 2

Views: 3742

Answers (1)

Nima Ebrazeh
Nima Ebrazeh

Reputation: 1306

I think that you should write app.toast instead of this.toast because this keyword is not available in asyncData.

but if app.toast does not work please try app.$toast too.

Updated Answer:

Right now I realized that $toast even not working in created lifecycle hook. This is because it's a client-side module and it is impossible to display toast on the server-side. For further details I recommend see this issue in github.

You can return for example an error variable from asyncData which is true if request failed. Then check in mounted lifecycle hook and if the value of error is set to true, then show the toast.

Upvotes: 2

Related Questions