Last active
May 17, 2022 17:04
-
-
Save ljaviertovar/599cccd27439a2df4665041e8ea4962d to your computer and use it in GitHub Desktop.
Clean up function in React, useEffect
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
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