Search code examples
reactjses6-promisearrow-functions

TypeError: Cannot read property 'then' of undefined although function returns promise


class Firebase {
  constructor() {
    app.initializeApp(firebaseConfig);
    this.auth = app.auth();
  }

  doCreateUserWithEmailAndPassword = (email, password) => {
   this.auth.createUserWithEmailAndPassword(email, password);
  };
}

When calling the Firebase.doCreateUserWithEmailAndPassword()-method with .then() I get the following error method:

TypeError: Cannot read property 'then' of undefined


Solution

  • I think many starters face this problem so I thought to share my solution.

    The { } around of the doCreateUserWithEmailAndPassword-method should have been removed so that the result of this.auth.createUserWithEmailAndPassword() is returned, because of the arrow function syntax

    or

    I could have kept the { } and added a return statement.

    So the right way would have been either:

     doCreateUserWithEmailAndPassword = (email, password) => 
        this.auth.createUserWithEmailAndPassword(email, password);
    
    

    or

     doCreateUserWithEmailAndPassword = (email, password) => {
        return this.auth.createUserWithEmailAndPassword(email, password);
      };