javascriptreact-nativereact-reduxfirebase-authentication

Capture error response from Firebase.auth() for display to user


I'm using React Native/Firebase/Redux to build a simple login system. I am trying to work out how to capture errors that happen as a result of failed login attempts.

Here's my authscreen.js:

const [alertShowing, setAlertShowing] = useState(false);
const [alertMessage, setAlertMessage] = useState('');
...

  function handleLogin() {
    const response = dispatch(login(email, password));
    console.log(response);
  }


actions.js:

export const login = (email, password) => {
  return async (dispatch) => {
    try {
      const response = await Firebase.auth().signInWithEmailAndPassword(email, password);
      dispatch(getUser(response.user.uid));
    } catch (e) {
        return e;
    }
  };
};

My console.log(response) above correctly shows me the error message, but this obviously isn't very useful to users. And please note too that I can log in properly when using correct credentials.

What I really want to do in my handleLogin() is check if the response is an error, and if so, setlAlertShowing(true) and setAlertMessage to what I've gotten back from the useDispatch hook so that I may display it nicely to the user.

How should I go about this? TIA.


Solution

  • Firebase errors messages are designed for developers and not standard users friendly. The solution is to identify authentication error code and map with user-friendly messages.

    list of error code https://firebase.google.com/docs/auth/admin/errors

    You can use function like this to map authError to meaningful error messages.

    function mapAuthCodeToMessage(authCode) {
      switch (authCode) {
        case "auth/invalid-password":
          return "Password provided is not corrected";
    
        case "auth/invalid-email":
          return "Email provided is invalid";
    
        // Many more authCode mapping here...
    
        default:
          return "";
      }
    }
    
    

    and use it later

    export const login = (email, password) => {
      return async (dispatch) => {
        try {
          const response = await Firebase.auth().signInWithEmailAndPassword(email, password);
          dispatch(getUser(response.user.uid));
        } catch (e) {
            dispatch({type:"authError",message:mapAuthCodeToMessage(e.code)}));
    
        }
      };
    };