DEV Community

Discussion on: Ways of Getting Data from API in React

olenadrugalya profile image
Olena Drugalya Author

Why would you need to cancel it? It performed just one time

pavermakov profile image
Pavel Ermakov

Imagine you are setting state on a successful response. If the component is unmounted before the response is back, you will get an error, something like "Unable to set state on unmounted component"

Thread Thread
olenadrugalya profile image
Olena Drugalya Author

In this case you can introduce a variable to track if the component is unmounted or not. If you use functional component, you can write something like this:
useEffect(() => {
let isMounted = true; // track whether component is mounted

  .then(result => {
    if (isMounted) {

return () => {
  // clean up
  isMounted = false;
Enter fullscreen mode Exit fullscreen mode

}, []); // only on "didMount"