DEV Community

Discussion on: Ways of Getting Data from API in React

 
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"