Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt - asyncData with multiple requests

In my application I have a seller page which displays products listed by that seller. I am using asyncData to get all data required for the page (better for SEO)

asyncData ({params, app, error }) {

    return app.$axios.$get(`/seller/${params.username}`).then(async sellerRes => {

        let [categoriesRes, reviewsRes, productsRes] = await Promise.all([
            app.$axios.$get(`/categories`),
            app.$axios.$get(`/seller/${params.username}/reviews`),
            app.$axios.$get(`/seller/${params.username}/products`)
        ])

        return {
            seller: sellerRes.data,
            metaTitle: sellerRes.data.name,
            categories: categoriesRes.data,
            reviewsSummary: reviewsRes.summary,
            products: productsRes.data,
        }

    }).catch(e => {
        error({ statusCode: 404, message: 'Seller not found' })
    });
},

Although this method does the job intended, I can't help but think I am doing this wrong.

When navigating to the page the nuxt progress bar displays twice (which is odd).

I've been searching for a while now to try and find examples of multiple requests in asyncData but there's not much out there.

Maybe I'm not supposed to call multiple requests in asyncData?

like image 919
itsliamoco Avatar asked Jan 10 '19 00:01

itsliamoco


1 Answers

Try to use async await, this is how you can run both requests in parallel:

async asyncData ({ $axios }) {
  const [categoriesRes, articlesRes] = await Promise.all([ 
    $axios.get('/fetch/categories'),
    $axios.get('/fetch/articles'),
  ])

  return {
    categories: categoriesRes.data,
    articles: articlesRes.data,
  }
},
like image 100
Andrew Savetchuk Avatar answered Sep 20 '22 11:09

Andrew Savetchuk