Vue: Best practices for handling multiple API calls





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















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 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 t hanfle 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 procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.










share|improve this question





























    0















    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 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 t hanfle 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 procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.










    share|improve this question

























      0












      0








      0








      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 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 t hanfle 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 procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.










      share|improve this question














      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 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 t hanfle 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 procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.






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





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






      javascript php laravel vue.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 21:23









      gabogabansgabogabans

      7318




      7318
























          2 Answers
          2






          active

          oldest

          votes


















          3














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





          share|improve this answer


























          • will I be able to catch errors for both calls with this, I'm a bit confused

            – gabogabans
            Nov 23 '18 at 0:52











          • 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.

            – Leandro Ferrero
            Nov 23 '18 at 19:52





















          0














          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.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438119%2fvue-best-practices-for-handling-multiple-api-calls%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














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





            share|improve this answer


























            • will I be able to catch errors for both calls with this, I'm a bit confused

              – gabogabans
              Nov 23 '18 at 0:52











            • 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.

              – Leandro Ferrero
              Nov 23 '18 at 19:52


















            3














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





            share|improve this answer


























            • will I be able to catch errors for both calls with this, I'm a bit confused

              – gabogabans
              Nov 23 '18 at 0:52











            • 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.

              – Leandro Ferrero
              Nov 23 '18 at 19:52
















            3












            3








            3







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





            share|improve this answer















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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 '18 at 21:55

























            answered Nov 22 '18 at 21:49









            Leandro FerreroLeandro Ferrero

            734




            734













            • will I be able to catch errors for both calls with this, I'm a bit confused

              – gabogabans
              Nov 23 '18 at 0:52











            • 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.

              – Leandro Ferrero
              Nov 23 '18 at 19:52





















            • will I be able to catch errors for both calls with this, I'm a bit confused

              – gabogabans
              Nov 23 '18 at 0:52











            • 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.

              – Leandro Ferrero
              Nov 23 '18 at 19:52



















            will I be able to catch errors for both calls with this, I'm a bit confused

            – gabogabans
            Nov 23 '18 at 0:52





            will I be able to catch errors for both calls with this, I'm a bit confused

            – gabogabans
            Nov 23 '18 at 0:52













            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.

            – Leandro Ferrero
            Nov 23 '18 at 19:52







            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.

            – Leandro Ferrero
            Nov 23 '18 at 19:52















            0














            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.






            share|improve this answer




























              0














              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.






              share|improve this answer


























                0












                0








                0







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 16:09









                MrozMroz

                508510




                508510






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438119%2fvue-best-practices-for-handling-multiple-api-calls%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to send String Array data to Server using php in android

                    Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                    Is anime1.com a legal site for watching anime?