Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'uid' of null

I am trying to log in with a phone number in my app with firebase but I am facing issue with the login process. I'm not able to login with a phone number in firebase but if I register with a phone number and redirect to the homepage it's working properly. I am using the same method to login, but I got the issue like TypeError: Cannot read property 'uid' of null but I an successfully getting all the console values. I don't know what is being the issue here. But that error is displaying in 3 times repeatedly,

Here is my code:

    renderLoginButton() {
        if (this.props.loading) {
          return (
            <Spinner size="large" />
          );
        }

        return (
          <Button
          style={{ alignSelf: 'flex-start' }}
            onPress={this.onLoginBtnClicked.bind(this)}
          >
            Login
          </Button>
        );
      }

onLoginBtnClicked() {

    const { contact, password } = this.props;
    const error =  Validator('password', password) ||  Validator('contact', contact);

    if (error !== null) {
      Alert.alert(error);
    } else {
          console.log('else');
        // this.props.loginUser({ contact, password});

        const mobileNo = '+91'+contact;
        firebase.auth().signInWithPhoneNumber(mobileNo)
        .then(confirmResult =>
            console.log(confirmResult),
            curr = firebase.auth(),
            console.log("curr"+JSON.stringify(curr)),
            this.setState({ data: curr}),
            NavigationService.navigate('Home')
        )
        .catch(error => console(error.message) );
    }

}

CustomDrawerComponent.js

    import React, { Component } from 'react';
import { View, Image, Text } from 'react-native';
import { DrawerItems } from 'react-navigation';
import { connect } from 'react-redux';

import { fetchUserDetails } from '../actions';

class CustomDrawerContentComponent extends Component {

  state = {
    uri: '',
    isfailed: ''
  }

  componentWillMount() {
    this.props.fetchUserDetails();
  }

  componentWillReceiveProps(nextProps) {
    let uri = '';
    if (nextProps.ProfilePic !== '') {
      uri = nextProps.ProfilePic;
      this.setState({ uri, isfailed: false });
    } else {
      uri = '../images/ic_person_24px.png';
      this.setState({ uri, isfailed: true });
    }

    this.setState({ uri });
  }

  renderProfileImage() {
    if (!this.state.isfailed) {
      return (
        <Image
          style={styles.profileImageStyle}
          source={{ uri: (this.state.uri) }}
        />
      );
    }
    return (
      <Image
        style={styles.profileImageStyle}
        source={require('../images/ic_person_24px.png')}
      />
    );
  }

  render() {
    console.log('Profile Pic :: ', this.props.ProfilePic);
    return (
      <View style={styles.container}>
        {this.renderProfileImage()}
        <Text style={styles.textStyle}>
          {this.props.name} - {this.props.category}
        </Text>
        <DrawerItems {...this.props} />
      </View>
    );
  }
}

const styles = {
  container: {
    flex: 1,
    paddingLeft: 10
  },
  textStyle: {
    fontSize: 14,
    textAlign: 'left',
    color: '#000000'
  },
  profileImageStyle: {
    alignSelf: 'flex-start',
    marginTop: 16,
    padding: 10,
    width: 40,
    height: 40,
    borderRadius: 75
  }
};

const mapStateToProps = state => {
  const { userprofile } = state;
  return userprofile;
};

export default connect(mapStateToProps, { fetchUserDetails })(CustomDrawerContentComponent);

callStack:

enter image description hereenter image description here

like image 546
Mahi Parmar Avatar asked Sep 10 '18 09:09

Mahi Parmar


1 Answers

Why does the user return as undefined (or even null)?

You know there’s a logged in user, you just logged in, heck, you can even see the user object in chrome dev tools.

Then why is it still returning undefined? There’s a straight answer to it.

You’re fetching the user object BEFORE that object is ready to be used.

Now, this can happen because of several different reasons, but if you follow this 2 "rules" you won’t see that error again.

Rule #1: Move it out of the constructor()

When you have something like:

constructor(){
  this.userId = firebase.auth().currentUser.uid
}

Over half of the time that page loads, the constructor is going to try to get the user before the user is ready, the app is blocking it because the page isn’t fully loaded, so you’re going to be trying to access uid of a property that just isn’t there yet.

When you get your page fully loaded, you can now call to get the currentUser.uid

Rule #2: Make it an Observable

There’s another approach you can take, that previous Firebase call we just made: firebase.auth().currentUser is synchronous. We can make it asynchronous by subscribing to the auth observable instead.

/**
   * When the App component mounts, we listen for any authentication
   * state changes in Firebase.
   * Once subscribed, the 'user' parameter will either be null 
   * (logged out) or an Object (logged in)
   */
  componentDidMount() {
    this.authSubscription = firebase.auth().onAuthStateChanged((user) => {
      this.setState({
        loading: false,
        user,
      });
    });
  }
  /**
   * Don't forget to stop listening for authentication state changes
   * when the component unmounts.
   */
  componentWillUnmount() {
    this.authSubscription();
  }
  render() {
    // The application is initialising
    if (this.state.loading) return null;
    // The user is an Object, so they're logged in
    if (this.state.user) return <LoggedIn />;
    // The user is null, so they're logged out
    return <LoggedOut />;
  }
}

Source article: Why does Firebase return undefined when fetching the uid?

A good tutorial for React Native will be here: Getting started with Firebase Authentication on React Native Since, your code did not show much, I hope you make an update to your question to show more code, so I might be able to look through.

like image 173
Angus Tay Avatar answered Oct 14 '22 23:10

Angus Tay