top of page
Search

Search with Ionic and Firebase

  • Writer: Fire Focus
    Fire Focus
  • Sep 28, 2020
  • 1 min read

Introduction


Hi there, in this video I will show you how you can create a simple user search with Ionic and Firebase Realtime Database.I have some sample users in my database.Each user has name, username, profile picture.I will perform search on username of users.


Setup Searchbar


Using ion-searchbar, I implemented a searchbar that has ionChange event.


search.page.html

<ion-searchbar mode="ios" animated placeholder="Search for usernames..." debounce=1000 (ionChange)="search($event)"></ion-searchbar>

Realtime Search


Before continue, import firebase and initialize searchedUsers array (to store the search results).


search.page.ts

import * as firebase from "firebase";

searchedUsers = [];

Next, write the code for real search.The search(evt) method triggers everytime there is a change in ion-searchbar.I get the input from user and convert it to lowercase .If there is a input then, start searching for usernames.Otherwise clear searchedUsers array.


I done search with the help of orderByChild("username") filter and uses startAt(lowerCaseKey), endAt(lowerCaseKey + "\uf8ff").The character \uf8ff used in the query is a very high code point in the Unicode range (it is a Private Usage Area [PUA] code). Because it is after most regular characters in Unicode, the query matches all values that start with queryText(here lowerCaseKey).


search.page.ts

search(evt) {
    var key: string = evt.target.value;
    var lowerCaseKey = key.toLowerCase();

    if (lowerCaseKey.length > 0) {
      firebase.database().ref("users").orderByChild("username").startAt(lowerCaseKey).endAt(lowerCaseKey + "\uf8ff").once("value", snapshot => {
          this.searchedUsers = [];
          snapshot.forEach(childSnap => {
            this.searchedUsers.push(childSnap.val());
          })
        })
    }
    else {
      this.searchedUsers = [];
    }
  }

Display Results


Let's display the results in searchedUsers array in search page.


search.page.html

<ion-item lines="none" *ngFor="let user of searchedUsers">
    <ion-avatar slot="start">
      <img src="{{user.dp}}" />
    </ion-avatar>
    <ion-label>
      <h2>
        {{user.name}}
      </h2>
      <p>
        @{{user.username}}
      </p>
    </ion-label>
</ion-item>

Comentários


Never Miss a Post. Subscribe Now!

Subscribe Fire Focus to get notified when we post something.Cheers!

Thanks for submitting!

"If you want something you've never had, you must be willing to do something you've never done"

bottom of page