Skip to content

Instantly share code, notes, and snippets.

@aderbas
Created November 19, 2020 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aderbas/187c3ed23db7d6ece9748a5858a8f0d5 to your computer and use it in GitHub Desktop.
Save aderbas/187c3ed23db7d6ece9748a5858a8f0d5 to your computer and use it in GitHub Desktop.
Cancel fetch when React component will unmount
/**
* Component test
*/
class MyComponent extends React.Component {
async fetchData(){
try{
const res = await fetch(
'<endpoint>', {
method: 'get',
signal: this.abortController.signal
}
);
// TO-DO
}catch(err){ /** TO-DO */ }
}
componentDidMount(){
this.abortController = new window.AbortController();
this.fetchData();
}
componentWillUnmount(){
this.abortController.abort();
}
render(){
return (
<div>Whatever</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment