Reputation: 77
So I am currently working on a game and I'm developing the signup page. As I'm using firebase authentication, I am required to use Firestore in order to store extra data on the users.
The code I'm using to sign up a user is as follows:
firebase.auth().createUserWithEmailAndPassword(app.email.trim(), app.password).then(function(result){
firebase.firestore().collection("userData").doc(result.user.uid).set({
score: 0,
gamesPlayed: 0,
wins: 0
}).catch(function(error){
app.errorMessage = error.message;
})
}).catch(function(error) {
// Handle Errors here.
app.errorCode = error.code;
app.errorMessage = error.message;
// ...
});
This code works fine on its own (I also have similar methods for signing in with other providers). However, on the same page I am also checking if the user is already signed in so they can be redirected.
firebase.auth().onAuthStateChanged(function(user){
if (user) {
window.location.href = '/index.html'
}
});
This also works fine.
The issue that I'm having is that when the user creates an account the user is redirected to the index page before the Firestore document is set. I assume this is the issue as if I comment out the redirect it seems to work just fine.
So my question is how can I ensure that the Firestore document is created before the user is redirected to the index page?
Thanks!
Upvotes: 0
Views: 77
Reputation: 2849
You can check if user is a newly signed up user in this way. firebase.auth().currentUser.metadata.creationTime === firebase.auth().currentUser.metadata.lastSignInTime
You can disable routing here, and define your own routing when user signs up.
firebase.auth().onAuthStateChanged(function(user){
if (user) {
if (firebase.auth().currentUser.metadata.creationTime !==
firebase.auth().currentUser.metadata.lastSignInTime) {
window.location.href = '/index.html'
}
}
});
Upvotes: 1