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
?
To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature.
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.
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();
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With