Skip to content
Advertisement

Can a Firebase error message template or Alert be customised to show custom Alerts?

I am working on a React App. The app has basic auth features. Here is the code below.

export async function registration(email, password, firstName, phone) {
  try {
    await firebase.auth().createUserWithEmailAndPassword(email, password);
    const currentUser = firebase.auth().currentUser;

const db = firebase.firestore();
db.collection("users").doc(currentUser.uid).set({
  email: currentUser.email,
  firstName: firstName,
  phone: phone,
  password: password,
});


} catch (err) {
    Alert.alert("Please Use Another Email ID", err.message);
  }
}

The issue here is that i am trying to create a custom alert for a specific error that is “The Email ID Already Exists”. But Firebase has its own predefined error template defined for it.

And when I replace with a custom code mentioned below,

 Alert.alert("Please Use Another Email ID", "This email ID already exists. If issue persists, contact support", [
  {
    text: "Ok",
    onPress: () => null,
    style: "cancel",
  },
  {
    text: "Contact Support",
    onPress: () => Linking.openURL('mailto: example@email.com'),
  },
]);
return true;

}

it works, but shows the same alert for every error present.

Somone. help. I am relatively new to React and JS.

Advertisement

Answer

Write a custom function that takes in the auth error and displays an Alert accordingly:

export function processAuthError(authError: string) {
    if(authError.includes('user-not-found')) {
        Alert.alert('User not found', 'You probably have to sign up first.')
    } else if(authError.includes('wrong-password')) {
        Alert.alert('Wrong password', 'Try again.')
    } else if(authError.includes('email-already-in-use')) {
        Alert.alert("Please Use Another Email ID", "This email ID already exists. If issue persists, contact support", [
            {
              text: "Ok",
              onPress: () => null,
              style: "cancel",
            },
            {
              text: "Contact Support",
              onPress: () => Linking.openURL('mailto: example@email.com'),
            },
          ]);
    } else if(authError.includes('network-request-failed')) {
        Alert.alert('Network error', 'Try again later or check your internet connection.')
    } else {
        Alert.alert('Unknown Error', 'Try again later.')
    }
}

This should actually work pretty much out of the box since I am using it in my own code with Firebase just slightly different. I just return a custom string and then display the Alert with it but since you wan’t custom Alerts this is the better way.

Advertisement