geek_programmer
geek_programmer

Reputation: 63

firebase.auth().onAuthStateChanged() returns undefined in react native

I am trying to get the auth status after refreshing the app and previously signing in but firebase.auth().onAuthStateChanged() gives undefined. The motive behind this is to either navigate to home screen or signIn screen by using the auth status.

import React, {Component} from 'react';
import {View} from 'react-native';
import firebase from 'firebase';
import {connect} from 'react-redux';
import {Spinner} from '../components/common';

class Switch extends Component {

  componentDidMount() {
    const userData = this.checkUser();
    this.switchContent(userData);
  }
  checkUser = () => {
    firebase.auth().onAuthStateChanged(async (userData) => {
      return userData;
    });
  };
  switchContent(userData) {
    console.log(userData);
    if (userData) {
      return this.props.persistantSignIn();
    }
    return this.props.navigation.push('SignInForm');
  }
  renderComponent() {
    return (
      <View style={{flex: 1}}>
        <Spinner />
      </View>
  }
  render() {
    return <View style={{flex:1}}>{this.renderComponent()}</View>;
  }
}

export default connect(null, {persistantSignIn})(Switch);

Upvotes: 1

Views: 738

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24194

The results of onAuthStateChanged (i.e. userData) should be processed within the anonymous function. Also note that until a user is signed in, userData will be null.

  componentDidMount() {
    firebase.auth().onAuthStateChanged( (userData) => {
      this.switchContent(userData);
    });
  }

There is no need to wrap firebase.auth().onAuthStateChanged within an anonymous function, unless, for example, you were to use useEffect, such as the following:

import { useEffect } from 'react';

...
  useEffect(() => {
    auth.onAuthStateChanged( userData => {
      this.switchContent(userData);
    })
  },[])

Upvotes: 1

Related Questions