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);

2 Answers 2

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
     );
  });
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);
  }
}

1 Comment

thank you, this helps me more than the selected answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.