Utilizing Axios to send multiple concurrent requests in Vue.js

What is the best way to simultaneously send multiple requests using axios and vue?

Answer №1

When it comes to using axios with React and Vue, the code is essentially the same.

Ensure you take a look at the axios documentation, as it provides thorough explanations.

Let's delve into an example here:

<template>
  <div>
    <button @click="make_requests_handler">Make multiple requests</button>
    {{message}} - {{first_request}} - {{second_request}}
  </div>
</template>

Here's the script section:

import axios from 'axios'

export default {
  data: () => ({
    message: 'no message',
    first_request: 'no request',
    second_request: 'no request'
  }),
  methods: {
    make_requests_handler() {
      this.message = 'Requests in progress'

      axios.all([
        this.request_1(),
        this.request_2()
      ])
        .then(axios.spread((first_response, second_response) => {
          this.message = 'Request finished'
          this.first_request = 'The response of first request is' + first_response.data.message
          this.second_request = 'The response of second request is' + second_response.data.message
        }))
    },
    request_1() {
     this.first_request: 'first request began'
     return axios.get('you_URL_here')
    },
    request_2() {
      this.second_request: 'second request began'
      return axios.get('another_URL', { params: 'example' })
    }
  }
}

Answer №2

If you have asynchronous tasks to handle, consider using Promise.all to execute them concurrently. As long as each task returns a promise, they can all run at the same time. You can use store.dispatch like in this example, or opt for axios calls or fetch.

In this instance, I'm triggering the calls when the vue component is created:

...
async created() {
    const posts = this.$store.dispatch(POSTS_LOAD);
    const comments = this.$store.dispatch(COMMENTS_LOAD);
    const users = this.$store.dispatch(USERS_LOAD);
    return await Promise.all([posts, comments, users])
        .then(() => {
            console.log('Data loaded successfully');
        });
}

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

Dealing with Unauthorized Errors (401) in an Axios React-Redux Application

I'm looking to handle the 401 unauthorized error that my server may output by dispatching an action. I've noticed many people using axios interceptors for this purpose. Could someone explain what interceptors are and guide me through implementing ...

Encountering a problem with Axios get request error in React and Redux when communicating with a Laravel 5.2 API

Currently, I am utilizing react alongside redux and axios for handling asynchronous actions. The backend is powered by Laravel 5.2 API which is located on a subdomain, while React resides on the main domain. However, whenever I attempt to make an async GET ...

Steps for launching a hyperlink in a browser on Vue Native

I'm having trouble finding information on how to properly use the Linking component in react-native. The resources available are limited, and I'm not sure if I am implementing it correctly... Below is what I have in my template: <nb-button :o ...

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

The Axios and TypeScript promise rejection error is displaying an unknown type- cannot identify

Currently, I am encountering an issue where I am unable to utilize a returned error from a promise rejection due to its lack of typability with Typescript. For instance, in the scenario where a signup request fails because the username is already taken, I ...

What is the method for sending an axios post request using the application/x-www-form-urlencoded content type?

How can I successfully send an axios post request using application/x-www-form-urlencoded? I am trying to include a refresh token in the request, but currently an empty object is being sent. However, I have verified that the token exists when checking "us ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...

SWR NextJS error remains unhandled despite being thrown

I'm struggling to manage errors thrown in my SWR fetcher. Currently, whenever an error is thrown, my app stops working and I see an "Unhandled Runtime Error". What I've been doing is throwing the error inside the fetcher function. Here's th ...

Using Node and Express to navigate to a URL within a React application

My goal is to open a user-provided URL in a reactjs application using node.js and express. I am incorporating material-ui and axios. Below is the code for the UI: This is a Proof of Concept for a UX testing project where the URL of the application to be ...

Combining Axios with repeated promises

I am facing an issue with a loop in my GET request on the axis, and I cannot figure out why. const [ state, setState ] = useState<any[]>([]); ids.forEach((id) => { getData(id) .then((smth: Map<string, any>[]) => getNeededData ...

Unsure about the differences between production and development phases?

Imagine a scenario where a React app interacts with an Express.js server. During development, the React app listens on localhost:3000 and the Express server on localhost:80. In the server-side code, we set the "Allowed origin" to be localhost:3000. The Re ...

Difficulty encountered in a Cast when using Router.put with mongoDB in a MERN application

Currently, I am trying to implement the router.put method for updating the Boolean value (isOn) in a toggle button. However, before making any changes, I decided to test it out and now I am encountering an issue. const express = require("express"); const ...

Encountering a Network Error and experiencing a blank dropdown with React-Select Async component

I recently integrated react-select into my React application. The API endpoint I'm working with responds with data structured like this: [ { value: 123, label: "Michael Carrick", first_name: "Michael", last_name: "Carrick", coun ...

When the Express API sends back a random number, Axios and React repeatedly call the API

I am facing an issue while creating a react component that displays a random number fetched from an API. The problem is that the number keeps re-rendering infinitely and the server console shows continuous requests from react. How can I fix this? I am curr ...

What is the best way to create a mock URL in axios for unit testing purposes?

Scenario In this application, the URL is only accessible in production and cannot be accessed locally. During unit testing, it becomes necessary to mock the response from that URL. Solution Refer to this helpful tutorial for guidance. Current Implement ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

The issue of ECONNABORTED is being triggered by parameterized queries

Attempting to execute a GET request from the front end to retrieve the username in the row where user_id = 1 using parameterized queries. While hard-coded queries are functioning correctly, parameterized queries result in the request being terminated and d ...

The issue with fetching user profile data on the client-side in Next.js 14

I've run into a problem with client-side data fetching on my Next.js 14 project. More specifically, I'm trying to retrieve user profile information from a backend API using Axios within a component, but for some reason, the data isn't coming ...

Obtaining an Auth0 token from within React components can be achieved in multiple different ways

I've been using axios for my API requests and have set up an interceptor to automatically attach the token to each request. This way, I don't need to constantly fetch the token from within every component. However, I'm encountering a challen ...

Encountering a Persian query issue while using fetch or axios headers in Next.js error

As a developer using next.js, I am facing an issue with my code. I run a blog and need to search for a keyword in the titles of my posts. This excerpt shows part of my code: const [result, setresult] = useState([]); const [keyword, setkeyword] = useState ...