0
votes

I am getting this error from console 'Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.' This is my function:

useEffect(() => {
    let isMounted = true;
    const onSubscribe = () => {
      auth.onAuthStateChanged((userAuth) => {
        if (userAuth && isMounted) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth && isMounted) {
          dispatch(logout());
        }
      });
    };
    onSubscribe();
    return () => {
      isMounted = false;
    };
  }, []);

I tried this way too

  useEffect(() => {;
    const onSubscribe = () => {
      auth.onAuthStateChanged((userAuth) => {
        if (userAuth) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth) {
          dispatch(logout());
        }
      });
    };
    onSubscribe();
    return () => {
      onSubscribe()
    };
  }, []);

1
Does removing isMounted = false; from the first example help you? - Tushar Shahi

1 Answers

0
votes

Can you try it like this:


useEffect(() => {
    const unsubscribe =  auth.onAuthStateChanged((userAuth) => {
        if (userAuth && isMounted) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth && isMounted) {
          dispatch(logout());
        }
      });
    
    return unsubscribe;
  }, []);