lolekbezlolek
lolekbezlolek

Reputation: 11

How to make createUserWithEmailAndPassword wait to set firestore?

I want to create a user with the data contained in firestore. I do this byway.

auth().createUserWithEmailAndPassword.then(() => {
  firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid).set({
    ...
   })
})

But this automatically creates the user and does not wait until the user is created in firestore. The user is immediately redirected by onAuthStateChange to the logged-in user screen. How to fix it? I'm using react-native.

Upvotes: 1

Views: 474

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50920

If you want to perform certain actions after the user is created or logs in then you must unsubscribe from the onAuthStateChanged observer:

const unsubscribe = firebase.auth().onAuthStateChanged(...)

unsubscribe()


function signUp() {
  unsubscribe() // detach auth observer before sign up

  auth().createUserWithEmailAndPassword.then(() => { 
 
 
 
 
 firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid).set({ ... }).then(() => {
      console.log('User created')
      // manually redirect now
      window.location.href = '/dashboard'
    })
  })
}

Upvotes: 1

Related Questions