Show error as alert on firebase authentication with react native

I am using this function in my react native app but it crashes my app, though it shows me errors on my emulator as a console, how shall i use alert to show whatever the error is to the user instead of crashing the app?

  signup =(email,password) =>{
try{
    firebase.auth().createUserWithEmailAndPassword(email,password)

    .then(() => this.props.navigation.navigate('home')) } 
    catch(error){
        alert("not valid"`enter code here`)
    }

   }

Upvotes: 1

Views: 12623

Answers (3)

solomon Yunana
solomon Yunana

Reputation: 439

I think you can't use an async function or a promise within a try block i have done that before and it resulted to the same issue as urs u should use only then and catch and try removing the try statement i hope it helps

Upvotes: 0

Praveen
Praveen

Reputation: 343

You can Display your custom alert messages using the switch case on error codes:

import {Alert} from 'react-native';

   try{
    firebase.auth().createUserWithEmailAndPassword(email,password)
      .then(() => this.props.navigation.navigate('home'))
      .catch(error => {   
        switch(error.code) {
          case 'auth/email-already-in-use':
                Alert.alert('Email already in use !')
                break;
       }
     })
   }catch(err){
      alert("Error : ", err);
   }

If you want to display the message directly from firebase :

   try{
    firebase.auth().createUserWithEmailAndPassword(email,password)
      .then(() => this.props.navigation.navigate('home'))
      .catch(error => {   
        alert(error.message);
     })
   }catch(err){
      alert(err);
   }

Upvotes: 14

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

Why not

 signup =(email,password) =>{
     try{
        firebase.auth().createUserWithEmailAndPassword(email,password)
          .then(() => this.props.navigation.navigate('home'))
          .catch(error => {
           alert("Error occurred", error)
         })
       }catch(err){
          alert("Error occurred", err);
        }
   }

Upvotes: 1

Related Questions