How to cancel or abort ajax requests in axios in a React app?

Estimated read time 2 min read

In order to cancel or abort AJAX requests in Axios in a React app, you can use the CancelToken and axios.CancelToken.source() method. Here are the steps to cancel a request:

  1. First, you need to create a cancel token using the CancelToken method provided by Axios:
const source = axios.CancelToken.source();
  1. Next, you need to add the cancelToken property to your Axios request with the token you created in the previous step:
axios.get('/api/data', { cancelToken: source.token })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log('Request canceled');
    } else {
      console.log(error);
    }
  });
  1. To cancel the request, you simply need to call the cancel method on the token source:
source.cancel('Operation canceled by the user.');
  1. You can also add a cancel button in your React app to cancel the request. Here’s an example:
function MyComponent() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const source = axios.CancelToken.source();

  const fetchData = () => {
    axios.get('/api/data', { cancelToken: source.token })
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        if (axios.isCancel(error)) {
          setError('Request canceled');
        } else {
          setError('Error fetching data');
        }
      });
  };

  const cancelRequest = () => {
    source.cancel('Operation canceled by the user.');
  };

  return (
    <div>
      {data ? (
        <div>{data}</div>
      ) : (
        <button onClick={fetchData}>Fetch Data</button>
      )}
      {error && <div>{error}</div>}
      {data && <button onClick={cancelRequest}>Cancel Request</button>}
    </div>
  );
}

In this example, we define a functional component named “MyComponent” that uses the useState hook to keep track of the data and error state.

We also define a fetchData function that makes an Axios request to fetch data and sets the data and error state accordingly.

We use the cancelRequest function to cancel the Axios request and set the error state to “Request canceled”.

We add a “Fetch Data” button to trigger the fetchData function and a “Cancel Request” button that calls the cancelRequest function if data has been fetched.

By using the CancelToken and axios.CancelToken.source() method provided by Axios, we can easily cancel AJAX requests in a React app.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply