user6097845
user6097845

Reputation: 1437

Firebase how to createUserWithEmailAndPassword and a user record at the same time?

Using Firebase, I'd like to do the following:

  1. Create a new user using FirebaseAuth (using createUserWithEmailAndPassword)
  2. Create a record for this new user in FireStore, where the document ID = user ID (adding fields such as name, role, gender etc.)

The problem is that once createUserWithEmailAndPassword is successful, an authStateChanges is triggered, and It's impossible to create the user record now...

How can I achieve this rather basic flow using Firebase's API?
Can I only achieve that using the Firebase Admin SDK?

Upvotes: 0

Views: 193

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50930

The problem is that once createUserWithEmailAndPassword is successful, an authStateChanges is triggered, and It's impossible to create the user record now...

Generally you would unsubscribe from the observer if you want to run some actions after registration like this:

const unsub = onAuthStateChanged(...);

const register = async () => {
  unsub(); // observer will not trigger on state changes
  // create user 
  // add document to Firestore
}

Alternatively, you can use Firebase Authentication Triggers to create document for user using Cloud Functions.

Upvotes: 1

Related Questions