Skip to content

Instantly share code, notes, and snippets.

@ljaviertovar
Last active May 17, 2022 17:04
Show Gist options
  • Save ljaviertovar/599cccd27439a2df4665041e8ea4962d to your computer and use it in GitHub Desktop.
Save ljaviertovar/599cccd27439a2df4665041e8ea4962d to your computer and use it in GitHub Desktop.
Clean up function in React, useEffect
useEffect(() => {
//create a controller
let controller = new AbortController();
(async () => {
try {
const response = await fetch(API,
{
// connect the controller with the fetch request
signal: controller.signal,
},
);
// handle success
setList(await response.json());
// remove the controller
controller = null;
} catch (e) {
// Handle the error
}
})();
//aborts the request when the component umounts
return () => controller?.abort();
},[]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment