Firebase.default.auth().currentUser.uid is null after createUserWithEmailAndPassword()

余生长醉 提交于 2020-07-23 07:48:27

问题


I'm trying to create a new document on my "users" collection on Firebase for any new user created on the Signup screen for my React-Native app, and the document is supposed to include the new user's uid, first name, last name, phone number, and date of birth. The issue is, after I use createUserWithEmailAndPassword to create a user, when I try to grab the uid with currentUser.uid, I get the following error: null is not an object (evaluating '_Firebase.default.auth().currentUser.uid').

I've been experimenting with ways to get the new user's "uid" in the .then statement following createUserWithEmailAndPassword and also creating the new document within the .then statement but I haven't gotten any luck with that yet. How should I modify my code so that I'm able to successfully create a new "users" document after successfully creating a user?

Below is my code from my handleSignUp function that is called when my "Sign Up" button is clicked:

handleSignUp = () => {
    Firebase.auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then(() => this.props.navigation.navigate("Main"))
      .catch((error) => this.setState({ errorMessage: error.message }));

    if (Firebase.auth().currentUser.uid) {
      const user = {
        uid: Firebase.auth().currentUser.uid,
        firstName: this.state.firstName,
        lastName: this.state.lastName,
        phone: this.state.phone,
        email: this.state.email,
        dob: this.state.dob
      };
      db.collection("users").doc(response.user.uid).set(user);
    }
  }; 

回答1:


If you want to:

  1. Create a user
  2. Write their details to the database
  3. Navigate to a new page

You'll need to make sure you do these steps in that order, and use the promises returned by each step to make sure things happen at the right time:

Firebase.auth()
  .createUserWithEmailAndPassword(this.state.email, this.state.password)
  .then((credentials) => {
      const user = {
        uid: credentials.user.uid,
        firstName: this.state.firstName,
        lastName: this.state.lastName,
        phone: this.state.phone,
        email: this.state.email,
        dob: this.state.dob
      };
      return db.collection("users").doc(response.user.uid).set(user);
  }).then(() => {
      this.props.navigation.navigate("Main")
  }).catch((error) => this.setState({ errorMessage: error.message }));


来源:https://stackoverflow.com/questions/61218790/firebase-default-auth-currentuser-uid-is-null-after-createuserwithemailandpass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!