I have two files, an App.js
where I set up my React Navigation StackNavigator along with my firebase instance and a Login.js
where I login users.
I am trying to detect if a user has already logged in (thru firebase persistent login) but for some reason, my firebase instance is not being detected in Login.js
's componentDidMount()
. This doesn't make sense to me because elsewhere in my Login.js
, I call fxns on my firebase instance, like logging in with Google.
How should I arrange the firebase initialization/auth check to ensure the firebase instance is detected correctly along with the persistent auth check?
I have already looked at this question but that person seems to have a different problem as they are only concerned with the firebase instance in a single file.
Relevant portions of App.js
import { StackNavigator } from 'react-navigation';
import * as firebase from 'firebase';
import 'firebase/firestore';
import Login from './components/login';
const Application = StackNavigator({
Login: { screen: Login,
navigationOptions: {
title: 'Login',
}
},
SignUp: { screen: SignUp,
navigationOptions: {
title: 'Signup',
}
},
Home: { screen: Home,
navigationOptions: {
title: 'Home'
}
},
});
const firebaseConfig = {
apiKey: "APIKEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "BUCKET",
}
export default class App extends React.Component {
componentDidMount(){
//if no instance exists, initialize one
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
}
render() {
return (
<Application/>
);
}
}
Relevant portion of Login.js
import * as firebase from 'firebase';
import Home from './home';
export default class Login extends React.Component {
constructor(props){
super(props)
this.state = {
isLoggingIn: true,
authFlag: false,
}
}
componentDidMount() {
//error is on the following line
firebase.auth().onAuthStateChanged((user) => {
if(!this.state.authFlag){
this.setState({ authFlag: true })
//persistent success, take user to Home
if(user){
this.props.navigation.navigate('Home');
return;
}
//user hasn't logged in before, must log in
else{
this.setState({isLoggingIn: false});
return;
}
}
});
}
}