4

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);
A_A
  • 310
  • 4
  • 13

2 Answers2

10

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
     );
  });
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • Even though this works, when you have many axios calls this gets messy. The answer using async/await by Nicholas Kajoh is much simpler and cleaner. – Jessica May 24 '22 at 19:07
3

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);
  }
}
Nicholas Kajoh
  • 1,451
  • 3
  • 19
  • 28