Skip to content

Instantly share code, notes, and snippets.

@adeelibr
Last active April 20, 2024 00:50
Show Gist options
  • Save adeelibr/d8f3f8859e2929f3f1adb80992f1dc09 to your computer and use it in GitHub Desktop.
Save adeelibr/d8f3f8859e2929f3f1adb80992f1dc09 to your computer and use it in GitHub Desktop.
Abort Controllers In Axios
import React, { Component } from 'react';
import axios from 'axios';
class Example extends Component {
signal = axios.CancelToken.source();
state = {
isLoading: false,
user: {},
}
componentDidMount() {
this.onLoadUser();
}
componentWillUnmount() {
this.signal.cancel('Api is being canceled');
}
onLoadUser = async () => {
try {
this.setState({ isLoading: true });
const response = await axios.get('https://randomuser.me/api/', {
cancelToken: this.signal.token,
})
this.setState({ user: response.data, isLoading: true });
} catch (err) {
if (axios.isCancel(err)) {
console.log('Error: ', err.message); // => prints: Api is being canceled
} else {
this.setState({ isLoading: false });
}
}
}
render() {
return (
<div>
<pre>{JSON.stringify(this.state.user, null, 2)}</pre>
</div>
)
}
}
@danielnagel
Copy link

Thanks man, helped me just as i needed it.

@adeelibr
Copy link
Author

If you want more in-depth knowledge of Abort Controllers, I wrote this article which might help you as well https://medium.com/free-code-camp/how-to-work-with-react-the-right-way-to-avoid-some-common-pitfalls-fc9eb5e34d9e
Cheers =)

@maxpaynestory
Copy link

Line 44 is extra inside the script and need to be removed.

@adeelibr
Copy link
Author

@maxpaynestory good catch 👍 fixed it.

@gonzaloamadio
Copy link

Have you done this but with redux? I mean, the axios call in an action creator, but still the cancellation from the component

@adeelibr
Copy link
Author

Can be done, the principals are the same for AbortController

@SoetZombie
Copy link

Since https://github.com/axios/axios#cancellation cancel token API proposal was withdrawn will this still work ?

@adeelibr
Copy link
Author

adeelibr commented Sep 3, 2020

Since https://github.com/axios/axios#cancellation cancel token API proposal was withdrawn will this still work ?

The concept of Abort Controller still works :))

@saksham-tj
Copy link

Any snippet on how to use it with Hooks (useEffect) ?
Does it works fine in the cleanup function of useEffect?

@adeelibr
Copy link
Author

@saksham-tj have a look at this stackoverflow thread https://stackoverflow.com/a/61056569/4921319

@adeelibr
Copy link
Author

Here is another amazing article by @kentcdodds on abort controllers usage in functional components i.e, hooks https://epicreact.dev/myths-about-useeffect/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment