• Skip to primary navigation
  • Skip to content

JAVEBRATT

Ionic Framework Tutorials

Looking for something?

  • Firebase Guides
  • About Me
  • Books
  • Firebase FREE Course
  • Firestore FREE Course
  • Let’s Talk

Implement a Search Bar on your Ionic app to filter your Firebase data

November 16, 2016 by javebratt 95 Comments

Last updated on April 8th, 2018 |

Introduction

As you probably know by now, Firebase is a noSQL database, something a lot of people really like.

But if you come from a SQL background, like I do, sometimes things that are easy for other people end up being a real challenge for us.

I want to show you one way I found on how to integrate a search-bar with Firebase, so that you can start typing and your Ionic app filters all the data in real time.

By the end of this post, you’ll be able to integrate a search-bar with Firebase from your Ionic 2 app, making data filtering easy on yourself without multiple database calls on keystroke.

Let’s get coding

The first thing you’ll need is to create an configure your app, I usually write the creation and configuration process in every post, but it’s making it harder for me to keep them up-to-date.

So if you need to know how to create and initialize your Firebase app, just read this tutorial first.

Also, if you click on the link above to get the source code, you’ll have access to my Firebase database with dummy data, which has a list of all the countries in the world ready to be used for this example.

The View

The first thing we’ll do is to create our view, it’s going to be something really simple, open the home.html file and create the search bar component and a list to loop through the countries.

<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-list>
  <ion-item *ngFor="let country of countryList">
    <h2> {{ country.name }} </h2>
    <h3> Code: <strong>{{ country.code }}</strong> </h3>
  </ion-item>
</ion-list>

The <ion-searchbar> is an Ionic 2 component that gives us a really nice looking search bar at the top of our file (also remove padding from ion-content so it doesn’t look weird).

And the list is looping through an array called countryList, showing our users the country’s name and code.

Now our job is to connect that search bar with the list, so every time the user types something the list gets updated.

The code

Go ahead and open home.ts and the first thing we’ll do is to import Firebase, after all, we need to get our data from somewhere 😛

import firebase from 'firebase';

Now that Firebase is imported, we’re going to create a couple of variables just before the constructor:

public countryList:Array<any>;
public loadedCountryList:Array<any>;
public countryRef:firebase.database.Reference;
  • countryRef: Is for creating a database reference so we can pull the data from Firebase.
  • countryList: Is to store the list of countries we’re pulling from Firebase.
  • loadedCountryList: Is a bit of a hack, that I will explain when we get to it 🙂

Now, go inside your constructor and create the database reference:

this.countryRef = firebase.database().ref('/countries');

That will open a reference to our Firebase database under the /countries node.

After that, we’re going to pull our data from Firebase, but before, let me explain something.

There are 2 ways of using a search bar to query data:

  • Query the data real-time from the database, meaning it will send a query on every keystroke.
  • Pull the data and query it in your phone, meaning it pulls the data once and then filters that array.

We’re going to use the second method, because:

  • You can only query for the exact value in Firebase, so if you query for ‘United’ you won’t get ‘United States of America’ as a result.
  • If you manage to pull that off, you’ll still be sending a hit to the database on every single keystroke.

Now that we got that out of the way, let’s pull the data from Firebase into the countryList array:

this.countryRef.on('value', countryList => {
  let countries = [];
  countryList.forEach( country => {
    countries.push(country.val());
    return false;
  });

  this.countryList = countries;
  this.loadedCountryList = countries;
});

We’re creating a countries array that we’ll use to store the Firebase data temporally.

We’ll loop through the country list and push it into the countries array.

Once that’s done, we assign both countryList and loadedCountryList the value of countries.

By now you should be wondering WTF am I creating an extra array just to store the same data, so it’s time for a little story.

A few months ago, I spent an entire day debugging this same thing, I was trying to filter through a list of US colleges, the list had over 2K items.

Every time you type something in the search bar (as you’ll see next) it tries to initialize the countryList array and then filter it to see if the string you entered matches an object from the list.

That’s easy to understand, and it’s the behavior you’ll expect, but somehow, it just wasn’t working for me. Wanna guess why?

It turns out that my data was being returned as a promise, and the list was so big that by the time it was ready to be used the initialize function had already happened.

And it was trying to initialize an undefined array, so everything was breaking 😛

So I came up with a little hack, and created 2 arrays, that way, when I need to initialize my data on keystroke, I just assign the value of the “backup” array, that happens on the spot, and my filter method then filters the right array.

So, now that you know why it’s there, let’s create the initialize function that we’ll use in our filter:

initializeItems(): void {
  this.countryList = this.loadedCountryList;
}

firebase search bar

See? Every time we need to initialize our list, we’ll just use the ready-to-use loadedCountryList instead of calling the data again from Firebase.

And now we just need to create the getItems() function that is going to run on every keystroke on our search bar.

getItems(searchbar) {
  // Reset items back to all of the items
  this.initializeItems();

  // set q to the value of the searchbar
  var q = searchbar.srcElement.value;


  // if the value is an empty string don't filter the items
  if (!q) {
    return;
  }

  this.countryList = this.countryList.filter((v) => {
    if(v.name && q) {
      if (v.name.toLowerCase().indexOf(q.toLowerCase()) > -1) {
        return true;
      }
      return false;
    }
  });

  console.log(q, this.countryList.length);

}

Every time the function gets called, it:

  • Initializes the countryList array.
  • Sets q as what’s currently inside the search bar.
  • Checks if q is empty (if you were deleting) and returns nothing if it is.
  • It checks the string against the value of the name property of our countries.

Right now you should have a working search bar that’s filtering against a list on your Firebase database.

search bar firebase

If you want to take a deeper dive on Ionic + Firebase you should go through my FREE course: Build your first Firebase powered Ionic app.

Related

Filed Under: Ionic & Firebase

Copyright © 2018 · Genesis Sample on Genesis Framework · WordPress · Log in