When making network requests with Axios, you may need to cancel certain requests. For example, when a user navigates away from the page or a component unmounts, you may want to cancel ongoing requests to prevent unnecessary resource consumption and potential state update issues. Axios provides a mechanism to cancel requests, and you can handle the cancelled request state.
In Axios, cancelling requests typically involves the following steps:
- Create a
CancelTokensource usingCancelToken.source(). - Include this cancel token in the Axios request configuration.
- Call the
cancel()method on the cancel token when you want to cancel a request. - Within the catch block of the request, verify if the error resulted from cancellation using the
axios.isCancel()function.
Here is an example of how to capture the cancelled state in Axios:
javascriptimport axios from 'axios'; // Create a CancelToken source const source = axios.CancelToken.source(); // Initiate a request and pass the cancel token axios.get('/some/path', { cancelToken: source.token }).then(response => { // Handle response console.log(response); }).catch(error => { // Capture the error and check if it was caused by cancellation if (axios.isCancel(error)) { console.log('Request was cancelled:', error.message); } else { // Handle other errors console.log('An error occurred:', error); } }); // Assume at some point you want to cancel the above request // For instance, when a component unmounts or conditions change source.cancel('Cancel request reason description');
In this example, if the request is cancelled, the catch block will capture an error. You can use the axios.isCancel() function to determine if the error was due to cancellation. If so, implement the appropriate logic, such as updating the state or informing the user. The parameter 'Cancel request reason description' is optional, allowing you to specify a custom cancellation reason, which will be included as the message property of the error object.