Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Using the Firebase Real-Time Database

Save for later
  • 5 min read
  • 18 Jan 2017

article-image

In this post, we are going to look at how to use the Firebase real-time database, along with an example. Here we are writing and reading data from the database using multiple platforms. To do this, we first need a server script that is adding data, and secondly we need a component that pulls the data from the Firebase database.

Step 1 - Server Script to collect data

Digest an XML feed and transfer the data into the Firebase real-time database. The script runs as cronjob frequently to refresh the data.

Step 2 - App Component

Subscribe to the data from a JavaScript component, in this case, React-Native.

About Firebase

Now that those two steps are complete, let's take a step back and talk about Google Firebase. Firebase offers a range of services such as a real-time database, authentication, cloud notifications, storage, and much more. You can find the full feature list here. Firebase covers three platforms: iOS, Android, and Web.

The server script uses the Firebases JavaScript Web API.

Having data in this real-time database allows us to query the data from all three platforms (iOS, Android, Web), and in addition, the real-time database allows us to subscribe (listen) to a database path (query), or to query a path once.

Step 1 - Digest XML feed and transfer into Firebase

Firebase Set Up
The first thing you need to do is to set up a Google Firebase project here

In the app, click on "Add another App" and choose Web, a pop-up will show you the configuration. You can copy paste your config into the example script.

Now you need to set the rules for your Firebase database. You should make yourself familiar with the database access rules. In my example, the path latestMarkets/ is open for write and read. In a real-world production app, you would have to secure this, having authentication for the write permissions.

Here are the database rules to get started:

{
    "rules": {
        "users": {
            "$uid": {
                ".read": "$uid === auth.uid",
                ".write": "$uid === auth.uid"
            }
        },
        "latestMarkets": {
            ".read": true,
            ".write": true
        }
    }
}

using-firebase-real-time-database-img-0

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime

The Server Script Code

The XML feed contains stock market data and is frequently changing, except on the weekend.

To build the server script, some NPM packages are needed:

  • Firebase
  • Request
  • xml2json
  • babel-preset-es2015
  • Require modules and configure Firebase web api:
    const Firebase = require('firebase');
    const request = require('request');
    const parser = require('xml2json');
    
    // firebase access config
    const config = {
        apiKey: "apikey",
        authDomain: "authdomain",
        databaseURL: "dburl",
        storageBucket: "optional",
        messagingSenderId: "optional"
    }
    
    // init firebase
    Firebase.initializeApp(config)
    [/Code]
    

I write JavaScript code in ES6. It is much more fun. It is a simple script, so let's have a look at the code that is relevant to Firebase.

  • The code below is inserting or overwriting data in the database. For this script, I am happy to overwrite data:
    Firebase.database().ref('latestMarkets/'+value.Symbol).set({
                Symbol: value.Symbol,
                Bid: value.Bid,
                Ask: value.Ask,
                High: value.High,
                Low: value.Low,
                Direction: value.Direction,
                Last: value.Last
            })
            .then((response) => {
                // callback
                callback(true)
            })
            .catch((error) => {
                // callback
                callback(error)
            })
    
  • Firebase Db first references the path:
    Firebase.database().ref('latestMarkets/'+value.Symbol)
  • And then the action you want to do:
    // insert/overwrite (promise)
    Firebase.database().ref('latestMarkets/'+value.Symbol).set({}).then((result)) 
    // get data once (promise)
    Firebase.database().ref('latestMarkets/'+value.Symbol).once('value').then((snapshot))
    // listen to db path, get data on change (callback)
    Firebase.database().ref('latestMarkets/'+value.Symbol).on('value', ((snapshot) => {}) 
    // ......
    
  • Here is the Github repository:

Displaying the data in a React-Native app

This code below will listen to a database path, on data change, all connected devices will synchronise the data:

Firebase.database().ref('latestMarkets/').on('value',    snapshot => {
    // do something with snapshot.val()
})

To close the listener, or unsubscribe the path, one can use "off":

Firebase.database().ref('latestMarkets/').off()

I’ve created an example react-native app to display the data:

The Github repository

Conclusion

In mobile app development, one big question is: "What database and cache solution can I use to provide online and offline capabilities?"

One way to look at this question is like you are starting a project from scratch. If so, you can fit your data into Firebase, and then this would be a great solution for you. Additionally, you can use it for both web and mobile apps. The great thing is that you don't need to write a particular API, and you can access data straight from JavaScript. On the other hand, if you have a project that uses MySQL for example, the Firebase real-time database won't help you much. You would need to have a remote API to connect to your database in this case.

But even if using the Firebase database isn't a good fit for your project, there are still other features, such as Firebase Storage or Cloud Messaging, which are very easy to use, and even though they are beyond the scope of this post, they are worth checking out.

About the author

Oliver Blumanski is a developer based out of Townsville, Australia. He has been a software developer since 2000, and can be found on GitHub at @blumanski.