0

I am using firebase in my react native project in expo CLI. I am trying to get the user information in another file that has been logged in. But for some reason i am facing the error that has been shown in this screenshot.

I tried initialising the firebase object in componentWillMount() as well as in the constructor. Yet it is throwing the same error, However if i come back and restart the app. It works just fine. Dashboard.js

import React, { Component } from 'react'
import { Text, View , StyleSheet } from 'react-native'
import * as firebase from 'firebase';
import firebaseConfig from '../config';
if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
  }
export class DashBoard extends Component {
    constructor()
    {
        super();  
    }
    render() {
            return (
                <View style={styles.container}>
                    <Text>Hello {firebase.auth().currentUser.email} </Text>
                </View>
            )
    }
}

export default DashBoard;

const styles= StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: 'center'
  }

})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Rahul Malik
  • 11
  • 1
  • 2

1 Answers1

3

When the application starts, Firebase may need to communicate with its servers to check if the user authentication is still valid. This happens asynchronously, and while this is going on, firebase.auth().currentUser will return null. So that's why your <Text>Hello {firebase.auth().currentUser.email} </Text> doesn't work: you're calling .email on null.

The solution is to check if the user is authenticated:

<Text>Hello {firebase.auth().currentUser ? firebase.auth().currentUser.email : "unknown user"} </Text>

You'll typically want to do this in your regular JavaScript code, instead of in the render() method as it makes the code a bit harder to read.

In fact, you'll likely want to push the user into the state of your object, and refresh it when the authentication state changes. To do this, you can attach a so-called auth state listener and call setState from its callback:

componentWillMount() {
  firebase.auth().addAuthStateChangedListener((user) => {
    this.setState({ user });
  });
}

And then in your render method you'd do:

<Text>Hello {user ? user.email : "unknown user"} </Text>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807