Last active
April 1, 2023 13:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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