问题
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:
- Create a user
- Write their details to the database
- 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