Lygis
Lygis

Reputation: 100

react useEffect clean up function

I have post component where I have useEffect in which photo is set inside state. If I click to other links to fast I get error "Can't perform a React state update on an unmounted component." So it tells that I need to clean up, but no matter what I try to read online I cant figure out how to do cleaning properly and still get same error. This is what I have now.


const ignore = useRef(true);
const [postImage, setPostImage] = useState();

useEffect(() => {
    if (ignore) {
      if (postPhoto) {
        storageRef
          .child(postPhoto)
          .getDownloadURL()
          .then((url) => {
            setPostImage(url);
          });
      }
    }

    if (pathname === "/profile" || pathname === `/profile/${params.user}`) {
      setShow(false);
    } else {
      setShow(true);
    }
    return () => (ignore.current = false);
  }, [postData]);

How should clean up look like? It is something that I struggle to understand the most in past weeks.

Upvotes: 1

Views: 291

Answers (1)

lissettdm
lissettdm

Reputation: 13078

The problem is that setPostImage(url) runs when component is unmounted. To avoid this error check if ignore.current is true before updating the state:

storageRef
       .child(postPhoto)
       .getDownloadURL()
       .then((url) => {
          if(ignore.current) setPostImage(url); //--> here
       });

Upvotes: 1

Related Questions