简体   繁体   中英

Javascript Firebase Authentication and Firestore: Page Redirects Before Saving User Data

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!

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'
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM