Home > Software design >  How to get the last Axios call of a function?
How to get the last Axios call of a function?

Time:10-08

I have a JS function that executes when a user click on an image and call an axios request to my backend and get a price, the problem is that the user can click different images at any time and the backend takes 5-10 seconds to get back the response and the price is updated many times because the user could be clicked 5 different images (block images is not an option).

How can I solve to only get the price of the last image that user clicked and ignore other requests?

CodePudding user response:

From version v0.22.0 Axios support AbortController to cancel requests. You could first create an abort controller which you abort before fetching a new request. Something like this:

const controller = new AbortController();

function handleClick(){

  // cancel the request
  controller.abort();

  axios.get('/foo/bar', {
     signal: controller.signal
  }).then(function(response) {
     //...
  });
}

Checkout the oficial Axios docs on this topic.

CodePudding user response:

You could debounce the function making the request. Debouncing sets a timer on a function that gets reset on subsequent calls of that specific function in the set time frame.

Here I used the debounce function provided by underscore.js

handleClick () {
  _.debounce(loadData, 300); // Debounce calls to load data by 300ms
}

loadData () {
  // sends the axios request to fetch pricing info
}

For example: The user clicks on an image, handleClick is called. If the user does not click again on any image within 300ms loadDatais called and the request is excecuted.

If the user does click an image within the specified 300ms the time starts again; Thus, only the last click in the given time frame counts.

CodePudding user response:

I think you can use the abort controller to cancel the request when the user clicks on another image.

  • Related