Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: Best practices for handling multiple API calls

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.

like image 457
gabogabans Avatar asked Sep 14 '25 09:09

gabogabans


1 Answers

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
  }));
like image 93
Leandro Ferrero Avatar answered Sep 16 '25 23:09

Leandro Ferrero