Skip to content

Instantly share code, notes, and snippets.

@tjunghans
Last active April 1, 2023 13:44
Show Gist options
  • Save tjunghans/da50cc29f3f965d587db99c2f44813f1 to your computer and use it in GitHub Desktop.
Save tjunghans/da50cc29f3f965d587db99c2f44813f1 to your computer and use it in GitHub Desktop.
Example of a functional React component with useEffect and the AbortController to cancel an async operation
// See https://gist.github.com/tjunghans/0129439ad12b37b98c72477156cddbce for the definition of `doSomethingAsync`.
function MyComponent({ someprop }) {
const [value, setValue] = React.useState("");
React.useEffect(() => {
// Create an instance of the AbortController that will
// be used to abort in the useEffect return.
const controller = new AbortController();
doSomethingAsync(someprop, {
signal: controller.signal
}).then((result) => {
// setValue must not be called after the component is unmounted.
// See https://medium.com/doctolib/react-stop-checking-if-your-component-is-mounted-3bb2568a4934.
setValue(result);
});
return () => {
controller.abort();
};
}, [someprop]);
return (
<div>
MyComponent...
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment