Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cancel/abort ajax request in axios

I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline can be managed by mouse's scroll. App sends ajax request for the actual data after any scroll event. Problem that processing of request at server can be more slow than next scroll event. In this case app can have several (2-3 usually) requests that already is deprecated because user scrolls further. it is a problem because every time at receiving of new data timeline begins redraw. (Because it's reactJS + flux) Because of this, the user sees the movement of the timeline back and forth several times. The easiest way to solve this problem, it just abort previous ajax request as in jQuery. For example:

    $(document).ready(     var xhr;      var fn = function(){         if(xhr && xhr.readyState != 4){             xhr.abort();         }         xhr = $.ajax({             url: 'ajax/progress.ftl',             success: function(data) {                 //do something             }         });     };      var interval = setInterval(fn, 500); ); 

How to cancel/abort requests in axios?

like image 241
Rajab Shakirov Avatar asked Jul 12 '16 12:07

Rajab Shakirov


People also ask

How do I cancel or abort Ajax request in Axios?

To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature.

How do I cancel API request?

Cancel Fetch request If you want to cancel a Fetch request, you need to use the AbortController API. You can use the constructor to create a new AbortController object. It has a read-only property AbortController.


2 Answers

Axios does not support canceling requests at the moment. Please see this issue for details.

UPDATE: Cancellation support was added in axios v0.15.

EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

Example:

const cancelTokenSource = axios.CancelToken.source();  axios.get('/user/12345', {   cancelToken: cancelTokenSource.token });  // Cancel request cancelTokenSource.cancel(); 
like image 54
Nick Uraltsev Avatar answered Sep 28 '22 00:09

Nick Uraltsev


Using useEffect hook:

useEffect(() => {   const ourRequest = Axios.CancelToken.source() // <-- 1st step    const fetchPost = async () => {     try {       const response = await Axios.get(`endpointURL`, {         cancelToken: ourRequest.token, // <-- 2nd step       })       console.log(response.data)       setPost(response.data)       setIsLoading(false)     } catch (err) {       console.log('There was a problem or request was cancelled.')     }   }   fetchPost()    return () => {     ourRequest.cancel() // <-- 3rd step   } }, []) 

Note: For POST request, pass cancelToken as 3rd argument

Axios.post(`endpointURL`, {data}, {  cancelToken: ourRequest.token, // 2nd step }) 
like image 24
Harshal Avatar answered Sep 28 '22 00:09

Harshal