PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] How to get the last Axios call of a function?

 October 12, 2022     axios, javascript, reactjs     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing