4

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 handle this situations, the best practices for multiple API calls, let's begin with the code I have.

I have an action where I gather all posts and all post categories from different API endpoints (Laravel for backend), I'm sure there's have to be a better way to handle this than how I'm doing it:

fetchAllPosts ({ commit }) {

        commit( 'SET_LOAD_STATUS', 1);
        axios.get('/posts')
        .then((response) => {
            commit('FETCH_ALL_POSTS',  response.data.posts )
            commit( 'SET_LOAD_STATUS', 2 );
        }, 
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', 3 );
        })
        axios.get('/postcategories')
        .then((response) => {
            commit('FETCH_ALL_POSTCATEGORIES',  response.data.postcategories )
            commit( 'SET_LOAD_STATUS', 2 );
        }, 
        (error) => {
            console.log(error);
            commit( 'SET_LOAD_STATUS', 3 );
        })
    },

First issue with my approach that I can think of is if the first API call fails but the second succeeds I will get a load status of 2 (2 equals success here) !

I only want to proceed with the commits if BOTH the first and second API call correctly fetch the data.

2 Answers 2

7

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

2 Comments

will I be able to catch errors for both calls with this, I'm a bit confused
Yes, on the link Part V: The Bottom Line you have an example of .all and as you can see, the catch intercepts all errors, so you need a extra logic to manage errors properly depending your application.
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.

Comments

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.