Timeout on Axios Requests











up vote
0
down vote

favorite












Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.



The issue is that the filter is done on real time and every change made via react causes an axios request.



Is there a way to put a timeout on the axios request so that I only fetch the last state?










share|improve this question






















  • use a debounce?
    – Daniel Lizik
    Sep 18 at 1:11















up vote
0
down vote

favorite












Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.



The issue is that the filter is done on real time and every change made via react causes an axios request.



Is there a way to put a timeout on the axios request so that I only fetch the last state?










share|improve this question






















  • use a debounce?
    – Daniel Lizik
    Sep 18 at 1:11













up vote
0
down vote

favorite









up vote
0
down vote

favorite











Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.



The issue is that the filter is done on real time and every change made via react causes an axios request.



Is there a way to put a timeout on the axios request so that I only fetch the last state?










share|improve this question













Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.



The issue is that the filter is done on real time and every change made via react causes an axios request.



Is there a way to put a timeout on the axios request so that I only fetch the last state?







reactjs timeout axios






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 17 at 22:09









lost9123193

1,732102859




1,732102859












  • use a debounce?
    – Daniel Lizik
    Sep 18 at 1:11


















  • use a debounce?
    – Daniel Lizik
    Sep 18 at 1:11
















use a debounce?
– Daniel Lizik
Sep 18 at 1:11




use a debounce?
– Daniel Lizik
Sep 18 at 1:11












2 Answers
2






active

oldest

votes

















up vote
1
down vote













The problem has two parts.



The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.



The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.



The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:



  onChange = e => {
this.fetchData(e.target.value);
};

fetchData = debounce(query => {
if (this._fetchDataCancellation) {
this._fetchDataCancellation.cancel();
}

this._fetchDataCancellation = CancelToken.source();

axios.get(url, {
cancelToken: this._fetchDataCancellation.token
})
.then(({ data }) => {
this.setState({ data });
})
.catch(err => {
// request was cancelled, not a real error
if (axios.isCancel(err))
return;

console.error(err);
});
}, 200);


Here is a demo.






share|improve this answer




























    up vote
    0
    down vote













    I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.



    But just in case you need to add a timeout during axios call, this can be achieved like -



    instance.get('/longRequest', {
    timeout: 5000
    });





    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',
      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%2f52376322%2ftimeout-on-axios-requests%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








      up vote
      1
      down vote













      The problem has two parts.



      The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.



      The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.



      The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:



        onChange = e => {
      this.fetchData(e.target.value);
      };

      fetchData = debounce(query => {
      if (this._fetchDataCancellation) {
      this._fetchDataCancellation.cancel();
      }

      this._fetchDataCancellation = CancelToken.source();

      axios.get(url, {
      cancelToken: this._fetchDataCancellation.token
      })
      .then(({ data }) => {
      this.setState({ data });
      })
      .catch(err => {
      // request was cancelled, not a real error
      if (axios.isCancel(err))
      return;

      console.error(err);
      });
      }, 200);


      Here is a demo.






      share|improve this answer

























        up vote
        1
        down vote













        The problem has two parts.



        The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.



        The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.



        The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:



          onChange = e => {
        this.fetchData(e.target.value);
        };

        fetchData = debounce(query => {
        if (this._fetchDataCancellation) {
        this._fetchDataCancellation.cancel();
        }

        this._fetchDataCancellation = CancelToken.source();

        axios.get(url, {
        cancelToken: this._fetchDataCancellation.token
        })
        .then(({ data }) => {
        this.setState({ data });
        })
        .catch(err => {
        // request was cancelled, not a real error
        if (axios.isCancel(err))
        return;

        console.error(err);
        });
        }, 200);


        Here is a demo.






        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          The problem has two parts.



          The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.



          The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.



          The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:



            onChange = e => {
          this.fetchData(e.target.value);
          };

          fetchData = debounce(query => {
          if (this._fetchDataCancellation) {
          this._fetchDataCancellation.cancel();
          }

          this._fetchDataCancellation = CancelToken.source();

          axios.get(url, {
          cancelToken: this._fetchDataCancellation.token
          })
          .then(({ data }) => {
          this.setState({ data });
          })
          .catch(err => {
          // request was cancelled, not a real error
          if (axios.isCancel(err))
          return;

          console.error(err);
          });
          }, 200);


          Here is a demo.






          share|improve this answer












          The problem has two parts.



          The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.



          The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.



          The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:



            onChange = e => {
          this.fetchData(e.target.value);
          };

          fetchData = debounce(query => {
          if (this._fetchDataCancellation) {
          this._fetchDataCancellation.cancel();
          }

          this._fetchDataCancellation = CancelToken.source();

          axios.get(url, {
          cancelToken: this._fetchDataCancellation.token
          })
          .then(({ data }) => {
          this.setState({ data });
          })
          .catch(err => {
          // request was cancelled, not a real error
          if (axios.isCancel(err))
          return;

          console.error(err);
          });
          }, 200);


          Here is a demo.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 18 at 1:49









          estus

          63.1k2193200




          63.1k2193200
























              up vote
              0
              down vote













              I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.



              But just in case you need to add a timeout during axios call, this can be achieved like -



              instance.get('/longRequest', {
              timeout: 5000
              });





              share|improve this answer

























                up vote
                0
                down vote













                I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.



                But just in case you need to add a timeout during axios call, this can be achieved like -



                instance.get('/longRequest', {
                timeout: 5000
                });





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.



                  But just in case you need to add a timeout during axios call, this can be achieved like -



                  instance.get('/longRequest', {
                  timeout: 5000
                  });





                  share|improve this answer












                  I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.



                  But just in case you need to add a timeout during axios call, this can be achieved like -



                  instance.get('/longRequest', {
                  timeout: 5000
                  });






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 18 at 5:21









                  Satyaki

                  3061415




                  3061415






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52376322%2ftimeout-on-axios-requests%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

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      SQL update select statement

                      'app-layout' is not a known element: how to share Component with different Modules