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.
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
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With