DEV Community

Discussion on: Ways of Getting Data from API in React

Collapse
 
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

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

request.get(url)
  .then(result => {
    if (isMounted) {
      setState(result);
    }
  });

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

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