Skip to content Skip to sidebar Skip to footer

Vue: Best Practices For Handling Multiple API Calls

So I found myself making more than one API call in my vuex action and this let me to wonder what would be the best way to hanfle this situatons, the best practices for multiple API

Solution 1:

I think you may want to read about promises.

On your example you are using Axios, which is a Promise based HTTP Client and that's great.

With Promises you can do several requests, and when all requests are successful you can THEN execute code.

With Axios you can do that with .all like this:

axios.all([getPosts(), getPostCategories()])
  .then(axios.spread(function (posts, categories) {
     // Both requests are now complete
  }));

Solution 2:

axios.all([
    axios.get(firstUrl),
    axios.get(secondUrl)
])
.then(axios.spread(function (response1, response2) {
    //response1 is the result of first call
    //response2 is the result of second call
}))
.catch(function (error) {

});

Note about catch(): It is called on the first failing request omitting the rest of the calls. So if the first call fails, catch() is called without even making the second request.


Post a Comment for "Vue: Best Practices For Handling Multiple API Calls"