Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing multiple requests Axios (Vue.js)

I am trying to perform two, non-concurrent request, but would like to use data from my first request before performing a second request. How can I achieve getting the data from the first request then using that data for the second request?

axios.get('/user/12345').then(response => this.arrayOne = response.data);
axios.get('/user/12345/' + this.arrayOne.name + '/permissions').then(response => this.arrayTwo = response.data);
like image 329
A_A Avatar asked Aug 31 '25 03:08

A_A


2 Answers

You can just nest the second axios call inside the first one.

axios.get('/user/12345').then(response => {
   this.arrayOne = response.data
   axios.get('/user/12345/' + this.arrayOne.name + '/permissions').then(
       response => this.arrayTwo = response.data
     );
  });
like image 199
Saurabh Avatar answered Sep 02 '25 16:09

Saurabh


You could also use async/await in ES2017:

myFunction = async () => {
  const response1 = await axios.get('/user/12345');
  this.arrayOne = response1.data;
  const response2 = await axios.get(`/user/12345/${this.arrayOne.name}/permissions`);
  this.arrayTwo = response2.data;
}
myFunction().catch(e => console.log(e));

OR

myFunction = async () => {
  try {
    const response1 = await axios.get('/user/12345');
    this.arrayOne = response1.data;
    const response2 = await axios.get(`/user/12345/${this.arrayOne.name}/permissions`);
    this.arrayTwo = response2.data;
  } catch(e) {
    console.log(e);
  }
}
like image 28
Nicholas Kajoh Avatar answered Sep 02 '25 18:09

Nicholas Kajoh