Exploring the Power of Nuxt's asyncData Feature for Handling Multiple Requests

Within my application, there is a seller page showcasing products listed by the specific seller. Utilizing asyncData to retrieve all necessary data for this page has been beneficial in terms of 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 the current approach gets the job done, I have some doubts about its correctness.

Upon navigating to the page, I've noticed that the Nuxt progress bar appears twice, which seems unusual.

I've spent some time searching for examples of handling multiple requests in asyncData, but resources on this seem scarce.

Could it be that making multiple requests within asyncData might not be the recommended practice?

Answer №1

To maximize efficiency, consider implementing async await to run multiple requests simultaneously:

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

  return {
    categories: categoriesRes.data,
    articles: articlesRes.data,
  }
},

Answer №2

Indeed, with the utilization of async await, the code appears much neater and cleaner.

<template>
  <div class="container">
    <h1>Request 1:</h1>
    <h1>{{ post.title }}</h1>
    <pre>{{ post.body }}</pre>
    <br />
    <h1>Request 2:</h1>
    <h1>{{ todos.title }}</h1>
    <pre>{{ todos.completed }}</pre>
  </div>
</template>

<script>
import axios from "axios";

export default {
  async asyncData({ params }) {
    // Taking advantage of ES6 async/await feature
    const posts = await axios.get(
      `https://jsonplaceholder.typicode.com/posts/${params.id}`
    );
    const todos = await axios.get(
      `https://jsonplaceholder.typicode.com/todos/${params.id}`
    );
    return { post: posts.data, todos: todos.data };
  },
  head() {
    return {
      title: this.post.title
    };
  }
};
</script>

Here you can find a functional sandbox version. (Remember to assign a value for the :id route parameter)

Answer №3

Is it possible?

fetchData ({params, app, error }) {

    return app.$axios.$get(`/seller/${params.username}`).then(sellerRes => {
        return Promise.all([
            app.$axios.$get(`/categories`),
            app.$axios.$get(`/seller/${params.username}/reviews`),
            app.$axios.$get(`/seller/${params.username}/products`)
        ]).then((categoriesRes, reviewsRes, productsRes) => {
            return {
                sellerInfo: sellerRes.data,
                pageTitle: sellerRes.data.name,
                availableCategories: categoriesRes.data,
                summaryOfReviews: reviewsRes.summary,
                productsList: productsRes.data,
            }
        })
    }).catch(e => {
        error({ statusCode: 404, message: 'Seller information not found' })
    });

},

This code snippet shows a series of promises being executed in sequence. The initial promise fetches data about the seller, and if successful, triggers additional requests for more information.

The fetchData method will wait for all promises to resolve before returning the final result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to Retrieve, Manipulate, and Merge JSON Data from Various Files

My knowledge of JavaScript is limited, but I am interested in uploading multiple JSON files, processing them, converting them to text, combining them, and downloading them into a single JS file. I have successfully achieved this for a single file, but I a ...

Incorporating URL addresses and pagination features using React.Js and Material-UI components

I have a functional component-page on my website, where I display a table that fetches data from an API. To improve user experience, I implemented pagination using the Material-UI library. While the pagination functionality works fine in updating the table ...

Can React.js components and packages be utilized in Vue.js, and vice versa?

Imagine you're working on a cutting-edge Angular project, but you want to incorporate components from your legacy Ember projects. You could easily achieve this by transferring and importing the component files into your new Angular project. I've ...

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

Vue's beforeRouteEnter hook patiently awaits for the child component to complete its request

My Vue app utilizes beforeRouteEnter to load data and prevent the undesirable "flash of unloaded content." Loading data on some pages is straightforward: async beforeRouteEnter(to, from, next) { const newestPosts = await getNewestPosts(); next(vm ...

Sending data over a network using Socket and node.js

Trying to update a location on a Google Map using socket.io and node.js. I have 2 different methods for updating the map. There may be some basic issue as I am new to this. 1) Method using an API call that works: app.post('/location', function( ...

Tips for sending web form data straight to Google Sheets without the need for an authentication page

Exploring the Concept I have a unique idea to develop a landing page with a form that captures visitors' email addresses in a Google Sheet. After discovering a helpful post containing a Google App script for this purpose, I followed the guidelines o ...

Unable to get the onchange event to trigger for a span element

Is there a way to trigger the onchange event on a span element that doesn't seem to be working? Here is the code I am using: Attempt 1 document.getElementById(seconds).addEventListener('change', (event: MutationEvent & { path: any }) =& ...

Tips for setting up a proxy with an enum

I am facing an issue with setting up a Proxy for an enum. Specifically, I have an enum where I want to assign a value to this.status using a Proxy. However, despite my expectations, the output "I have been set" does not appear in the console. Can anyone ex ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Bringing to life in Vue.js

I am a beginner with Vue.js and I have been attempting to integrate Materialize into my project. I have experimented with various plugins such as vue-materialize (https://github.com/paulpflug/vue-materialize) and vue-material-components (https://www.npmjs. ...

The error message "Evaluating this.props.navigation: undefined is not an object" indicates that there

In the navigation bar, I am trying to keep a touchable opacity at the top right. When this touchable opacity is pressed, I want to redirect the user to the home page. constructor(props) { super(props); this.state = { stAccntList: [], ...

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

The function will not be triggered when the form is submitted

I've set up this form to send data to the server-side. It's built in HTML/CSS with AngularJS as well. I made sure that the button is placed inside the form, a common mistake that can cause issues. However, despite my efforts, the function "onAddE ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Accessing elements from a controller in a nested ng-repeat in AngularJS

I am relatively new to the world of AngularJS and I've encountered a challenge that I can't seem to figure out. The issue lies within my nested ng-repeat view, as I have a nested comment system. Therefore, the view is built from an object structu ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

What is the best way to arrange cards in a specific order with breaks in between each flip

I am currently working on creating flip cards using HTML and CSS. I have successfully implemented the hover effect which flips the cards when hovered over. Now, my goal is to make the cards automatically flip one after the other at specific time intervals ...

Error: The text value is not defined

Hello, I am currently working on retrieving the selected value of an input when the input is focused with the tab key. Below is my code: HTML <input id='texteb' type="text" value='' /> <button> click </button> JS ...