Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt await async + vuex

Tags:

vue.js

nuxt.js

Im using nuxt and vuex. In vuex im getting data:

actions: {
    get_posts(ctx) {
      axios.get("http://vengdef.com/wp-json/wp/v2/posts").then(post => {
        let posts = post.data;


        if (!posts.length) return;

        let medias_list = "";
        posts.forEach(md => {
          medias_list += md.featured_media + ","
        });
        medias_list = medias_list.slice(0, -1);


        let author_list = "";
        posts.forEach(md => {
          author_list += md.author + ","
        });
        author_list = author_list.slice(0, -1);


        axios.all([
          axios.get("http://vengdef.com/wp-json/wp/v2/media?include=" + medias_list),
          axios.get("http://vengdef.com/wp-json/wp/v2/users?include=" + author_list),
          axios.get("http://vengdef.com/wp-json/wp/v2/categories"),
        ]).then(axios.spread((medias, authors, categories) => {

          ctx.commit("set_postlist", {medias, authors, categories} );

        })).catch((err) => {
          console.log(err)
        });


      })
    }
  },

In vuex state i have dynamic postlist from exaple below. How i can use it in Nuxt?

In nuxt i know async fetch and asyncData.

async fetch () {
    this.$store.dispatch("posts/get_posts");
}

Thats not working.

How i can say to nuxt, wait loading page, before vuex actions loading all data?


1 Answers

As you already mentioned there are:

  • fetch hook
  • asyncData

And differences are well described here

The reason why your code is not working might be in your store action. It should return a promise, try to add return before axios get method ->

get_posts(ctx) {
      return axios.get(...
    // ...

And then, on your page:

async fetch () {
    await this.$store.dispatch("posts/get_posts");
}

Also, in comment above you're saying that you dont want to commit data in store:

...load page only after vuex, i dont need to pass data in vuex

But you do it with this line:

ctx.commit("set_postlist", {medias, authors, categories} );

if you dont want to keep data in store, just replace line above with:

return Promise.resolve({ medias, authors, categories })

and get it on your page:

async fetch () {
    this.posts = await this.$store.dispatch("posts/get_posts");
    // now you can use posts in template 
}
like image 179
Yevhenii K. Avatar answered Feb 05 '26 10:02

Yevhenii K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!