'Why does not work correctly the cleanup function?

In the custom hook, there is a cleanup function, if the component is unmounted, then the states won't be updated.

Can you tell me why is the if condition in the catch block all the time skipped? The default value for the isCancelled is false , so it should work, but it does not. I have to get out the dispatch function from the if condition, and put before the condition. Why is that? I don't cancel the component, so the isCancelled should be false, but instead is true. Where has been changed the isCancelled from false to true. Thanks!

import { useEffect, useState } from 'react';
import { auth } from '../firebase/config';
import { signInWithEmailAndPassword } from 'firebase/auth';

import { useAuth } from '../context/AuthContext';

export const useLogin = () => {
  const [isCancelled, setIsCancelled] = useState(false);
  const [error, setError] = useState(null);
  const [isPending, setIsPending] = useState(false);
  const { dispatch } = useAuth();

  const login = async (email, password) => {
    console.log(auth.currentUser);
    setError(null);
    setIsPending(true);

    //sign user out
    try {
      const res = await signInWithEmailAndPassword(auth, email, password);
      console.log(auth.currentUser);
      console.log(res.user);

      //update state
      if (!isCancelled) {
        dispatch({ type: 'LOGIN', payload: res.user });
        setIsPending(false);
        setError(null);
      }
    } catch (error) {
      if (!isCancelled) {
        console.log(error.message);
        setError(error.message);
        setIsPending(false);
      }
    }
  };

  useEffect(() => {
    return () => setIsCancelled(true);
  }, []);

  return { login, error, isPending };
};



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source