DEV Community

Mohmed Ishak
Mohmed Ishak

Posted on

The Axios Cancel Token In React (Advanced React Made Simple)

Hey, React devs! So you're pretty comfortable with Hooks and components in React but can you write optimized code? In this article, I'm going to share with you a way to optimize Axios API calls in React.

The Problem

Mohmed Ishak

This is it. Image you're building a search bar with autosuggest feature or with feature that will immediately query for the relevant search results from the backend after every keystroke by the user. Now, for some reason, I'd like to search for "whale", and so I type "w", "h", followed by "a". By this time, the frontend would have made the API call to your server 3 times, which congests the server and makes your app slow.

The Solution

Is there any way to optimize it? Yes, thanks to Axios' cancel token feature. If only cancel token from Axios were implemented in previous scenario which I mentioned, every new request after every keystroke from the user will cancel the previous request(s) that were made to the server (provided that the request(s) have not been served), so only the latest request will get executed. What's the code behind it?

You can check out a super small article from Axios' docs using the following link (https://axios-http.com/docs/cancellation) or just copy the code snippet below which I'm sure you'll understand by just looking at it.

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

Top comments (4)

Collapse
 
nombrekeff profile image
Keff

I think that for the problem mention, you would be better just doing debouncing on your text field instead, no need to perform the api call. The theory behind debouncing is simple, each time the user enters a key you delay a function call by some amount, if another key is pressed the last function is canceled and a new call is delayed. Until one of the calls executes, then you perform the call to the API.

Collapse
 
ishakmohmed profile image
Mohmed Ishak

I just got to know debouncing from you. Thanks man.

Collapse
 
nombrekeff profile image
Keff

Great stuff! It's a really useful concept to know!

Collapse
 
johnbabu021 profile image
john • Edited

Cool I was searching for something like this ,just wondering canceling will work with signals also right??