Getting started with React Native and Firebase

James Marino
5 min readSep 7, 2016

--

I was first sceptical about Firebase, but after using it in action it seems like Firebase may be able to speed up conventional mobile and web app development — by a lot!

In a traditional mobile or web app development when you’re building something other than a text editor, chances are you will be using the MVC model: grabbing data from your server (or someone else's) and displaying it on your view. You also may have to put some sort of authentication on this data being retrieved, requiring an initial login and further access privileges for certain users.

This can get tedious, spin up an AWS EC2 instance, choose your server side environment and language, database setup and selection, domain names and DNS configuration, load balancing and scaling, VPC’s and Security Groups; a lot of work just to get your “simple” app rolling.

Firebase aims to solve all of this and make your backend truly minimal maintenance, taking things a step further than any other product I’ve seen, such as AWS’s Lambda.

So what is Firebase?

Firebase allows a seamless connection and integration between your data, users and authentication. It pretty much handles the Model and the Controller part of your MVC, leaving you just to worry about the view. It also allows for some cool concepts such as listening for database data changes, which can be implemented easier than you may think. And yes, it does incorporate a No-SQL database, similar to MongoDB.

Why Firebase + React Native

Fast development. Very fast development!

Firebase Setup: Your backend

Go to https://firebase.google.com and click “Go to Console” in the top right. Make sure you are using the latest version of Firebase and not https://www.firebaseio.com.

Create the new project and set your region

Next, go to the “Auth” tab > “Sign in method” tab and enable “Email/Password” as your Sign-in provider(s).

Click the “Add firebase to your web app” link on the home screen and note the config object, we will need this later for the front end setup

and that’s it! This is all we need to do to get our apps backend rolling. The rest will be done on the react native side. No code in the backend?, this is getting weird!

React Native: Your front end

Now that we have the “backend” set up, we can make a simple app that logs a user in or signs them up and allows them to add their mobile phone number to their account, which will be stored in the realtime database.

If you are not familiar with React Native, Facebook’s official docs are a good place to start.

Setup the initial react project — this may take a minute

$ react-native init FirebaseReactNative

Install the official Google Firebase NPM module

$ npm install --save firebase

Then, open the project up in WebStorm or your favourite IDE

Setting up the Login / Signup

Whenever using firebase, make sure you import the module

import * as firebase from "firebase";

First, initialise your application (find these values in the above “Add firebase to your web app” step)

firebase.initializeApp({
apiKey: "yourkeyhere",
authDomain: "projName-d0c3e.firebaseapp.com",
databaseURL: "https://projName-d0c3e.firebaseio.com",
storageBucket: "projName-d0c3e.appspot.com"
});

Add users via email using the following async function. If you are unfamiliar with Javascript ES7's new async await functionality check out this article. Note: React Native already supports async / await out of the box, there is no need to install any transpilers such as Babel

async signup(email, pass) {

try {
await firebase.auth()
.createUserWithEmailAndPassword(email, pass);

console.log("Account created");

// Navigate to the Home page, the user is auto logged in

} catch (error) {
console.log(error.toString())
}

}

Many of Firebase’s functions will return a promise, allowing you to utilise async await. In the example above, the signup function is run asynchronously, but the asynchronous functions inside will run synchronously when prefixed with “await”. This will allow the console.log(“Account created”) statement to run after the createUser Firebase function is done.

Here we can see a user is added to our Firebase app

Next we will create the login function, it is quite similar to the signup

async login(email, pass) {

try {
await firebase.auth()
.signInWithEmailAndPassword(email, pass);

console.log("Logged In!");

// Navigate to the Home page

} catch (error) {
console.log(error.toString())
}

}

Similarly with the logout

async logout() {

try {

await firebase.auth().signOut();

// Navigate to login view

} catch (error) {
console.log(error);
}

}

Storing the data in the realtime database

The realtime database stores data as JSON which is in typical No-SQL fashion of setting and getting key value pairs from a hierarchy of data, Realtime Database seems to be much like MongoDB.

Jumping Ahead: A user has just added their mobile number
import * as firebase from "firebase";

class Database {

/**
* Sets a users mobile number
*
@param userId
*
@param mobile
*
@returns {firebase.Promise<any>|!firebase.Promise.<void>}
*/
static setUserMobile(userId, mobile) {

let userMobilePath = "/user/" + userId + "/details";

return firebase.database().ref(userMobilePath).set({
mobile: mobile
})

}

/**
* Listen for changes to a users mobile number
*
@param userId
*
@param callback Users mobile number
*/
static listenUserMobile(userId, callback) {

let userMobilePath = "/user/" + userId + "/details";

firebase.database().ref(userMobilePath).on('value', (snapshot) => {

var mobile = "";

if (snapshot.val()) {
mobile = snapshot.val().mobile
}

callback(mobile)
});
}

}

module.exports = Database;

The above helper functions will store the mobile number and will retrieve changes to the users mobile number as they occur.

Authorising Access to the Data

One more thing you may want to consider is authorisation on your data. By default all database access is only able to be read and written to if the user is authenticated:

{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}

See the docs for more information of authentication on the Realtime Database: https://firebase.google.com/docs/database/security/

Complete App

You can find the complete app available on my Github, clone and just run:

$ npm install
$ react-native run-ios
Data being “changed” client side and updated on the server in realtime (and vice versa)

Being able to remove “the middle man” to integrate an apps backend on the fly is a great advantage, but as the project increases complexity will Firebase hold up? We will just have to find out!

--

--