user54517
user54517

Reputation: 2420

Firebase Auth authStateChanges trigger

I'm using firebase to authenticate a user and create a user in firestore database :

final auth.FirebaseAuth _firebaseAuth;

Future<void> signUp(
      {@required String email, @required String password}) async {
    assert(email != null && password != null);
    try {
      await _firebaseAuth.createUserWithEmailAndPassword(
          email: email, password: password);
      await createUserInDatabaseIfNew();
      
    } on Exception {
      throw SignUpFailure();
    }
  }

With firebase, once the method .createUserWithEmailAndPassword() is executed, it triggers right after the authStateChanges which I am using in my code to send the new user in the user stream, and eventually retrieve its data from the database

Stream<User> get user {
    return _firebaseAuth.authStateChanges().map((firebaseUser) {
      return firebaseUser == null ? User.empty : firebaseUser.toUser;
    });
  }
StreamSubscription<User> _userSubscription = _authenticationRepository.user.listen((user) {
          return add(AuthenticationUserChanged(user));}
if(event is AuthenticationUserChanged){
      if(event.user != User.empty){
        yield AuthenticationState.fetchingUser();
        User userFromDatabase;
        try{
          var documentSnapshot = await _firebaseUserRepository.getUser(event.user.id);
          userFromDatabase = User.fromEntity(UserEntity.fromSnapshot(documentSnapshot));
          yield AuthenticationState.authenticated(userFromDatabase); 
          
        }

The problem that I am facing, is that because of _firebaseAuth.createUserWithEmailAndPassword, _firebaseAuth.authStateChanges is triggerd before the user is created in the database, and eventually when I try to retrieve that user, it still does not exist in the database.

I would like _firebaseAuth.authStateChanges() to be triggered after my method createUserInDatabaseIfNew runs.

How could I achieve that ?

Upvotes: 1

Views: 1196

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

I would like _firebaseAuth.authStateChanges() to be triggered after my method createUserInDatabaseIfNew runs.

The auth state change listener fires when the user's authentication state change, which is when their sign in completes. There's no way to change this behavior, nor should there be.

If you want to trigger when the user's registration in your app has completed, you should respond to events that signal that. So if registration means that the user is written to the database, you can use a onSnapshot listener on the database to detect user registration.

You could even combine the two:

  1. Use an auth state change listener to detect when the sign in completes.
  2. Inside that auth state listener, then attach a snapshot listener for the user's registration document.

Upvotes: 1

Related Questions