Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios-Make multiple request at once (vue.js)

How to make multiple requests in parallel using axios and vue ?

like image 837
Ready Dev Avatar asked May 26 '18 06:05

Ready Dev


1 Answers

Since axios can be used by React and Vue it is pretty much the same code.

Make sure to read axios docs, you can understand it from there.

Anyway, I am going to show you an example:

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

And the script:

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(), //or direct the axios request
        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' })
    }
  }
}
like image 191
Roland Avatar answered Sep 28 '22 04:09

Roland