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

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

Error message in Vuejs: The injection "Symbol()" could not be found

I encountered an issue while using confirmdialog in primevue. The error message I received is: [Vue warn]: injection "Symbol()" not found I am unsure of the cause of this error and how to resolve it. Any assistance would be greatly appreciated ...

Ways to trigger an event or invoke a function after initializing Stripe JS

My checkout page is optimized with the new Stripe Payment Element for fast loading using SSR. However, I am facing an issue where the element sometimes causes the page to reload 2 or more times before functioning properly. Occasionally, it also displays ...

Incorrectly aligned highlighted labels are appearing on the Kendo chart category axis item labels

My current project involves using the kendo chart to generate charts, and I need specific labels to show up as bold text. To achieve this, I am utilizing the visual method which allows me to customize labels and render them with createVisual(). However, w ...

Sending a PDF document and JSON data via an AJAX POST request

I'm attempting to send a PDF document along with some JSON data in string format using an AJAX method in jQuery to an ASP.NET WEB API (2). Below are my attempts that are not working: JAVASCRIPT: // Obtaining the authorization token works fine var hea ...

Discover the secret to restricting JSON API functionality in your WordPress plugin

I am interested in using WordPress to build a website, specifically looking to export site posts using the JSON API. However, I encountered an issue when attempting to limit the displayed posts by category. Clicking on the "get_category_posts" link within ...

Using JavaScript to create a JSON object within a table

Currently, I am facing a challenge in creating a JSON object from an HTML table using JavaScript. While I can successfully retrieve the values of each cell in JavaScript, the issue lies in organizing and retrieving them as per my requirements. Here is the ...

Can you guide me on creating a post and get request using ReactJS, Axios, and Mailchimp?

I am brand new to ReactJS and I am currently working on developing an app that requires integration with Mailchimp to allow users to subscribe to a newsletter. I am looking for assistance on making a request using axios. Where should I input my API key? ...

Preserving form data using JavaScript exclusively upon submission

Hey there! I'm facing a little issue with a Form that has multiple checkboxes and a piece of JavaScript code designed to save the state of each checkbox when the user hits submit. My problem is that, currently, the checkbox state is being saved even i ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

Various SVG paths make up segments

I have created an intricate SVG file containing 35 different paths resembling train tracks. My next step is to break down these paths into 16 segments, allowing another SVG path (train) to smoothly traverse along them. The ultimate goal is to grant users ...

Every time I attempt to build a React application, I encounter the same error message. I even checked the log file, but it keeps showing the proxy error

An error occurred in the command prompt while installing packages. This process may take a few minutes. Installing react, react-dom, and react-scripts with cra-template... Error: ERR_SOCKET_TIMEOUT The network encountered a socket timeout while trying to ...

Turn off automatic spelling correction and predictive text in a content-editable section

I'm currently working on a cross-browser application using Script#. I've incorporated a contenteditable div where users can input text. However, I am facing an issue with the auto correct/auto completion feature altering the user's text. Co ...

Creating dynamic web pages with jQuery is a simple and effective

I am currently using jQuery to create HTML elements with specific classes and then append them together. However, the code I have written is not adding the generated HTML to the container as expected. There are no errors being produced but the HTML is not ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

What could be causing the lack of updates to my component in this todo list?

Based on my understanding, invoking an action in MobX should trigger a rerender for the observer. However, when I call the handleSubmit method in my AddTask component, it doesn't cause the TaskList observer to rerender. Should I also wrap AddTask in a ...

Remove the ID, class, and other attributes from an HTML string using JavaScript for sanitization purposes

Can someone help me with sanitizing HTML text provided by a user? The HTML code in question is as follows: var htmlStr = `<p id="test" class="mydemo">TEhis is test</p> <pre class="css"> &lt;html> &lt;body cl ...