'Cancel async API call from useEffect on unmount
I've got the API call as soon as the page loads in a useEffect hook, can I somehow cancel the request if the component unmounts?
useEffect(() => {
const callContract = async (): Promise<void> => {
try {
// ... call API here
} catch (err: any) {
console.log(err);
}
};
callContract();
}, []);
Solution 1:[1]
The useEffect return value is the unmount function:
useEffect(() => {
console.log("I got mounted");
return () => {
console.log("I got unmounted");
};
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmed Shaqanbi |
