fbpx
Firebase Promise

Firebase Promise

What is a Promise

Promise represent an eventual (asynchronous) value. When you are using a method that returns a promise then that method will either resolve or reject, in any case of resolve or reject, it calls all the callback functions that have been assigned via the then() or catch() methods. Let’s discus further on these two methods: .then() and catch():

  • then() method in firebase returns firebase Promise containing any type. this method is called when the Promise is resolved.
  • catch() method oppose the then() method as it only gets to be called when the Promise is rejected. It returns any type as well.

Now that I have explained the promise and the two methods that get called, I will walk you through a process of building a simple app that will allow a user to register and login using firebase. This will allow us to better understand the promises because we will be using the promise from firebase.

Start a app for promise

Our Project Setup

Start a new ionic project and you can give it any name, at this point I take you already know how to start a new ionic project but incase you are not familiar with it, you can check out the tutorial . Generate three pages namely: login, signup and home. Use the below commands to create your pages:

ionic generate page login
ionic generate page signup
ionic generate home

Login Html Page

  • Go to you html file of your login page and place two input component for email and password. Your input should use ngModel.
  • Have two buttons for login and register, the login button should call a login() method and the signup button should call a signup button.
  • Your login.html file should look this:

<ion-header>
  <ion-navbar>
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>

    <ion-item>
      <ion-label fixed>Email</ion-label>
      <ion-input type="text" value="" [(ngModel)]="email"></ion-input>
  </ion-item>
   <ion-item>
      <ion-label fixed>Password</ion-label>
      <ion-input type="password" [(ngModel)]="password"></ion-input>
    </ion-item>
  
  </ion-list>
  <button ion-button block (click)="login()">Login</button>
  <button ion-button block outline (click)="signup()">Signup</button>
</ion-content>

Signup Html Page

  • On your signup.html file, have three input fields for username, email and password.
  • Then have one button for sign up that calls signup() method.
  • Your html page should look like this:

<ion-header>
  <ion-navbar>
    <ion-title>Signup</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>

    <ion-item>
      <ion-label fixed>Username</ion-label>
      <ion-input type="text" value="" [(ngModel)]="username"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label fixed>Email</ion-label>
      <ion-input type="text" value="" [(ngModel)]="email"></ion-input>
    </ion-item>
  
    <ion-item>
      <ion-label fixed>Password</ion-label>
      <ion-input type="password" [(ngModel)]="password"></ion-input>
    </ion-item>
  
  </ion-list>

  <button ion-button block (click)="signup()">Signup</button>
</ion-content>

Firebase uses promises therefore in this tutorial we will use promise API that the firebase provides. It has a number of available auth providers such as email/password, phone number and also federated providers like Facebook, Google, Twitter, GitHub and more. For this tutorial I have focused on the email/password auth provider.

Now at this point we are ready to start implementing methods that will register and log in our users to the app. We will be using firebase.auth provider which returns a promise.

Implementing the method

For registering a user to firebase we will use createUserWithEmailAndPassword() method and for login we will use signinUserWithEmailAndPasswrod() method. Both these methods takes two parameters of email and password.  I have implement the method for login on the login.ts file and I also implemented the method for registration on the signup.ts file.  I have placed the code below:

 login(){
    firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(user => {
      if(user){
        var alert = this.alertCtrl.create({
          title: 'Login Successful',
          message: 'Welcome!',
          buttons: [{
            text:'Ok',
            handler: () =>{
              this.navCtrl.push(HomePage)
            }
          }]
        });
        alert.present();
      }
      }).catch(function(error){
      //error handling
      console.log(error);
      })
 }

  1. On line 2 
    • I used the signInWithEmailAndPassword and passed two value parameters from the user entry which is email and password.
    • The method returns a promise. The then() gets to be called if the promise is resolved.
  2.  On line 3-4
    • I used an alert controller to display a message in a alert dialog when the promise is resolve instead of reject.
  3. On line 16 to 20 
    • I have placed the catch method to handle errors just incase the promise is reject.
    • Please not that the catch method is optional but because of good coding standard procedure, you would want to handle your errors so you could know where the code is going wrong.

signup() {
 firebase.auth().createUserWithEmailAndPassword(this.email,this.password).then(user =>{
      if(user){
        
           var alert = this.alertCtrl.create({
            title: 'Successful Registration!',
            subTitle: 'You are successfully registered',
            buttons: [{
              text:'Ok',
              handler: () =>{
                this.navCtrl.push(HomePage)
              }
            }]
          });
          alert.present();
      }
    }).catch((function(error){
      // We handle our errors here
      console.log(error.message);
    }))
  }

  1. On line 1
    • I have used the createUserWithEmailAndPassword method. The .then() gets to be called when the promise calls the resolve.
  2. From line 3 to 20
    1. Here it’s basically the same thing as the login() method.

Alright, that’s it for now on promises. I hope this was helpful and you now have an understanding of the promises and it’s returns. Please do not forget to subscribe to get notification of new content on our page and shall you encounter any challenges on this tutorial please do not hesitate to contact us.

%d bloggers like this: