Issue
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?
Solution
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.
Answered By - Andres Abadia Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.