The beginners guide to React Native & Firebase

by Sona James

on February 7, 2018

Firebase.

Firebase is great for building real-time apps.Firebase synchronizes application state, and React re-renders the application UI based on state changes.

Firebase SetUp

React Native manages dependencies through npm. To install Firebase, run the following command at the root of the project.

npm install firebase –save

Open index.ios.js and add the following line to the top:

import * as firebase from ‘firebase’;

Then right above the component, initialize Firebase with your config values:

Real-time Database Listener

const firebaseDatabase = firebase.database();

Methods

goOffLine & goOnLine

Disconnects from the server (all Database operations will be completed offline).

The client automatically maintains a persistent connection to the Database server, which will remain active indefinitely and reconnect when disconnected. However, the goOffline() and goOnline() methods may be used to control the client connection in cases where a persistent connection is undesirable.

While offline, the client will no longer receive data updates from the Database.

Example

firebase.database().goOffline();

firebase.database().goOnline();

Ref

ref(path) returns firebase.database.Reference

Returns a Reference representing the location in the Database corresponding to the provided path. If no path is provided, the Reference will point to the root of the Database.

Returns

non-null firebase.database.Reference If a path is provided, a Reference pointing to the provided path. Otherwise, a Reference pointing to the root of the Database.

Examples

Ref From URL

refFromURL(url) returns firebase.database.Reference

Returns a Reference representing the location in the Database corresponding to the provided Firebase URL.

Note that all query parameters (orderBy, limitToLast, etc.) are ignored and are not applied to the returned Reference

Examples

firebase.database.DataSnapshot

A DataSnapshot contains data from a Database location.

Any time you read data from the Database, you receive the data as a DataSnapshot. A DataSnapshot is passed to the event callbacks you attach with on() or once(). You can extract the contents of the snapshot as a JavaScript object by calling the val() method. Alternatively, you can traverse into the snapshot by calling child() to return child snapshots (which you could then call val() on).

A DataSnapshot is an efficiently generated, immutable copy of the data at a Database location. It cannot be modified and will never change (to modify data, you always call the set() method on a Reference directly).

Key

The key (last part of the path) of the location of this DataSnapshot.

The last token in a Database location is considered its key. For example, “ada” is the key for the /users/ada/ node. Accessing the key on any DataSnapshot will return the key for the location that generated it. However, accessing the key on the root URL of a Database will return null.

Examples

Ref

The Reference for the location that generated this DataSnapshot.

Methods

Child

child(path) returns firebase.database.DataSnapshot

Gets another DataSnapshot for the location at the specified relative path.

Passing a relative path to the child() method of a DataSnapshot returns another DataSnapshot for the location at the specified relative path. The relative path can either be a simple child name (for example, “ada”) or a deeper, slash-separated path (for example, “ada/name/first”). If the child location has no data, an empty DataSnapshot (that is, a DataSnapshot whose value is null) is returned.

Example

Exits

exists() returns boolean

Returns true if this DataSnapshot contains any data. It is slightly more efficient than using snapshot.val() !== null

Returns

Boolean

Example

exportVal

exportVal() returns any type

Exports the entire contents of the DataSnapshot as a JavaScript object.

The exportVal() method is similar to val(), except priority information is included (if available), making it suitable for backing up your data.

Returns any type The DataSnapshot’s contents as a JavaScript value (Object, Array, string, number, boolean, or null).

forEach

forEach(action) returns boolean

Enumerates the top-level children in the DataSnapshot.

Because of the way JavaScript objects work, the ordering of data in the JavaScript object returned by val() is not guaranteed to match the ordering on the server nor the ordering of child_added events. That is where forEach() comes in handy. It guarantees the children of a DataSnapshot will be iterated in their query order.

If no explicit orderBy*() method is used, results are returned ordered by key (unless priorities are used, in which case, results are returned by priority).

Examples

getPriority

getPriority() returns (string, number, or null)

Gets the priority value of the data in this DataSnapshot.

Applications need not use priority but can order collections by ordinary properties (see Sorting and filtering data).

Returns

(string, number, or null)

hasChild

hasChild(path) returns boolean

Returns true if the specified child path has (non-null) data.

Returns

boolean true if data exists at the specified child path; else false.

Example

hasChildren

hasChildren() returns boolean

Returns whether or not the DataSnapshot has any non-null child properties.

You can use hasChildren() to determine if a DataSnapshot has any children. If it does, you can enumerate them using forEach(). If it doesn’t, then either this snapshot contains a primitive value (which can be retrieved with val()) or it is empty (in which case, val() will return null).

Returns

boolean true if this snapshot has any children; else false.

Example

numChildren

numChildren() returns number

Returns the number of child properties of this DataSnapshot.

Returns

Number

toJSON

toJSON() returns Object

Returns a JSON-serializable representation of this object.

Returns

nullable Object A JSON-serializable representation of this object.

Val

val() returns any type

Extracts a JavaScript value from a DataSnapshot.

Depending on the data in a DataSnapshot, the val() method may return a scalar type (string, number, or boolean), an array, or an object. It may also return null, indicating that the DataSnapshot is empty (contains no data).

Returns

any type The DataSnapshot’s contents as a JavaScript value (Object, Array, string, number, boolean, or null).

Example

Firebase.auth

Auth

auth(app) returns firebase.auth.Auth

Gets the Auth service for the default app or a given app.

firebase.auth() can be called with no arguments to access the default app’s Auth service or as firebase.auth(app) to access the Auth service associated with a specific app.

Examples

Persistance

An enumeration of the possible persistence mechanism types.

App

non-null firebase.app.App

The app associated with the Auth service instance.

Example

var app = auth.app;

CurrentUser

(firebase.User or null)

The currently signed-in user (or null).

LanguageCode

(string or null)

The current Auth instance’s language code. This is a readable/writable property. When set to null, the default Firebase Console language setting is applied. The language code will propagate to email action templates (password reset, email verification and email change revocation), SMS templates for phone authentication, reCAPTCHA verifier and OAuth popup/redirect operations provided the specified providers support localization with the language code specified.

Methods

confirmPasswordReset

confirmPasswordReset(code, newPassword) returns firebase.Promise containing void

Completes the password reset process, given a confirmation code and new password.

Error Codes

auth/expired-action-code

Thrown if the password reset code has expired.

auth/invalid-action-code

Thrown if the password reset code is invalid. This can happen if the code is malformed or has already been used.

auth/user-disabled

Thrown if the user corresponding to the given password reset code has been disabled.

auth/user-not-found

Thrown if there is no user corresponding to the password reset code. This may have happened if the user was deleted between when the code was issued and when this method was called.

auth/weak-password

Thrown if the new password is not strong enough.

Returns

non-null firebase.Promise containing void

createUserAndRetrieveDataWithEmailAndPassword

createUserAndRetrieveDataWithEmailAndPassword(email, password) returns firebase.Promisecontaining non-null firebase.auth.UserCredential

Creates a new user account associated with the specified email address and password and returns any additional user info data or credentials.

This method will be renamed to createUserWithEmailAndPassword replacing the existing method with the same name in the next major version change.

On successful creation of the user account, this user will also be signed in to your application.

User account creation can fail if the account already exists or the password is invalid.

Note: The email address acts as a unique identifier for the user and enables an email-based password reset. This function will create a new user account and set the initial user password.

Error Codes

auth/email-already-in-use

Thrown if there already exists an account with the given email address.

auth/invalid-email

Thrown if the email address is not valid.

auth/operation-not-allowed

Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.

auth/weak-password

Thrown if the password is not strong enough.

Returns

non-null firebase.Promise containing non-null firebase.auth.UserCredential

Example

confirmPasswordReset

confirmPasswordReset(code, newPassword) returns firebase.Promise containing void

Completes the password reset process, given a confirmation code and new password.

Error Codes

auth/expired-action-code

Thrown if the password reset code has expired.

auth/invalid-action-code

Thrown if the password reset code is invalid. This can happen if the code is malformed or has already been used.

auth/user-disabled

Thrown if the user corresponding to the given password reset code has been disabled.

auth/user-not-found

Thrown if there is no user corresponding to the password reset code. This may have happened if the user was deleted between when the code was issued and when this method was called.

auth/weak-password

Thrown if the new password is not strong enough

createUserAndRetrieveDataWithEmailAndPassword

createUserAndRetrieveDataWithEmailAndPassword(email, password) returns firebase.Promisecontaining non-null firebase.auth.UserCredential

Creates a new user account associated with the specified email address and password and returns any additional user info data or credentials.

This method will be renamed to createUserWithEmailAndPassword replacing the existing method with the same name in the next major version change.

On successful creation of the user account, this user will also be signed in to your application.

User account creation can fail if the account already exists or the password is invalid.

Note: The email address acts as a unique identifier for the user and enables an email-based password reset. This function will create a new user account and set the initial user password.

Error Codes

auth/email-already-in-use

Thrown if there already exists an account with the given email address.

auth/invalid-email

Thrown if the email address is not valid.

auth/operation-not-allowed

Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.

auth/weak-password

Thrown if the password is not strong enough.

Example

createUserWithEmailAndPassword

createUserWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.User

Creates a new user account associated with the specified email address and password.

This method will be deprecated and will be updated to resolve with afirebase.auth.UserCredential as is returned infirebase.auth.Auth#createUserAndRetrieveDataWithEmailAndPassword.

On successful creation of the user account, this user will also be signed in to your application.

User account creation can fail if the account already exists or the password is invalid.

Note: The email address acts as a unique identifier for the user and enables an email-based password reset. This function will create a new user account and set the initial user password.

Error Codes

auth/email-already-in-use

Thrown if there already exists an account with the given email address.

auth/invalid-email

Thrown if the email address is not valid.

auth/operation-not-allowed

Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.

auth/weak-password

Thrown if the password is not strong enough.

Example

fetchProvidersForEmail

fetchProvidersForEmail(email) returns firebase.Promise containing non-null Array of string

Gets the list of provider IDs that can be used to sign in for the given email address. Useful for an “identifier-first” sign-in flow.

Error Codes

auth/invalid-email

Thrown if the email address is not valid.

onAuthStateChanged

onAuthStateChanged(nextOrObserver, error, completed) returns function()

Adds an observer for changes to the user’s sign-in state.

Prior to 4.0.0, this triggered the observer when users were signed in, signed out, or when the user’s ID token changed in situations such as token expiry or password change. After 4.0.0, the observer is only triggered on sign-in or sign-out.

Example

onIdTokenChanged

Adds an observer for changes to the signed-in user’s ID token, which includes sign-in, sign-out, and token refresh events.

Example

sendPasswordResetEmail

sendPasswordResetEmail(email, actionCodeSettings) returns firebase.Promise containing void

Sends a password reset email to the given email address.

To complete the password reset, call firebase.auth.Auth#confirmPasswordReset with the code supplied in the email sent to the user, along with the new password specified by the user.

Error Codes

auth/invalid-email

Thrown if the email address is not valid.

auth/missing-android-pkg-name

An Android package name must be provided if the Android app is required to be installed.

auth/missing-continue-uri

A continue URL must be provided in the request.

auth/missing-ios-bundle-id

An iOS Bundle ID must be provided if an App Store ID is provided.

auth/invalid-continue-uri

The continue URL provided in the request is invalid.

auth/unauthorized-continue-url

The domain of the continue URL is not whitelisted. Whitelist the domain in the Firebase console.

auth/user-not-found

Thrown if there is no user corresponding to the email address.

Example

signInAndRetrieveDataWithCustomToken

signInAndRetrieveDataWithCustomToken(token) returns firebase.Promise containing non-null firebase.auth.UserCredential

Signs in a user asynchronously using a custom token and returns any additional user info data or credentials.

This method will be renamed to signInWithCustomToken replacing the existing method with the same name in the next major version change.

Custom tokens are used to integrate Firebase Auth with existing auth systems, and must be generated by the auth backend.

Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.

Error Codes

auth/custom-token-mismatch

Thrown if the custom token is for a different Firebase App.

auth/invalid-custom-token

Thrown if the custom token format is incorrect.

Example

signInAndRetrieveDataWithEmailAndPassword

signInAndRetrieveDataWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.auth.UserCredential

Asynchronously signs in using an email and password and returns any additional user info data or credentials.

This method will be renamed to signInWithEmailAndPassword replacing the existing method with the same name in the next major version change.

Fails with an error if the email address and password do not match.

Note: The user’s password is NOT the password used to access the user’s email account. The email address serves as a unique identifier for the user, and the password is used to access the user’s account in your Firebase project.

See also: firebase.auth.Auth#createUserAndRetrieveDataWithEmailAndPassword.

Error Codes

auth/invalid-email

Thrown if the email address is not valid.

auth/user-disabled

Thrown if the user corresponding to the given email has been disabled.

auth/user-not-found

Thrown if there is no user corresponding to the given email.

auth/wrong-password

Thrown if the password is invalid for the given email, or the account corresponding to the email does not have a password set.

Example

signInWithCustomToken

signInWithCustomToken(token) returns firebase.Promise containing non-null firebase.User

Asynchronously signs in using a custom token.

This method will be deprecated and will be updated to resolve with afirebase.auth.UserCredential as is returned infirebase.auth.Auth#signInAndRetrieveDataWithCustomToken

Custom tokens are used to integrate Firebase Auth with existing auth systems, and must be generated by the auth backend.

Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.

Error Codes

auth/custom-token-mismatch

Thrown if the custom token is for a different Firebase App.

auth/invalid-custom-token

Thrown if the custom token format is incorrect.

Example

signInWithEmailAndPassword

signInWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.User

Asynchronously signs in using an email and password.

This method will be deprecated and will be updated to resolve with afirebase.auth.UserCredential as is returned infirebase.auth.Auth#signInAndRetrieveDataWithEmailAndPassword.

Fails with an error if the email address and password do not match.

Note: The user’s password is NOT the password used to access the user’s email account. The email address serves as a unique identifier for the user, and the password is used to access the user’s account in your Firebase project.

Error Codes

auth/invalid-email

Thrown if the email address is not valid.

auth/user-disabled

Thrown if the user corresponding to the given email has been disabled.

auth/user-not-found

Thrown if there is no user corresponding to the given email.

auth/wrong-password

Thrown if the password is invalid for the given email, or the account corresponding to the email does not have a password set.

Example

Fire-base Event Types

Firebase offers several different event types for reading data. Some of the most commonly used ones are described below.

value

The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all the data including children.

child_changed

This event type is triggered when the data has changed.

 const updateChannel = createEventChannelUpdate();

 while (true) {

   const response = yield take(updateChannel);

}

function createEventChannelUpdate() {

 const dataRef = firebaseDatabase.ref();

 const listner = eventChannel((emit) => {

   dataRef.on(‘child_changed’, (snapshot) => {

     emit(snapshot);

   });

   return () => dataRef.off(listner);

 });

 return listner;

}

child_added

This event type will be triggered once for every player and every time a new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list.

const updateChannel = createEventChannelAdd();

 while (true) {

   const response = yield take(updateChannel);

}

function createEventChannelAdd() {

 const dataRef = firebaseDatabase.ref();

 const listner = eventChannel((emit) => {

   dataRef.on(‘child_added’, (snapshot) => {

     if (newItems) {

       emit(snapshot);

     }

   });

   return () => dataRef.off(listner);

 });

 return listner;

}

child_removed

If we want to get access of deleted data, we can use child_removed event type.

 const updateChannel = createEventChannelRemove();

 while (true) {

   const response = yield take(updateChannel);

}

function createEventChannelRemove() {

 const dataRef = firebaseDatabase.ref();

 const listner = eventChannel((emit) => {

   dataRef.on(‘child_removed’, (oldChildSnapshot) => {

     emit(oldChildSnapshot);

   });

   return () => dataRef.off(listner);

 });

 return listner;

}

 

 

 

 

 

 

 

 

 

 

  • Share this Article

GET IN TOUCH WITH iLEAF

  • We can initiate development process at the hour of your convenience
  • Discussion on the projects can be held for a stipulated duration
  • We will sign NDA and the talks will be secured
  • We’ll show you around our cherished designs
  • Briefing on technology
  • Guaranteed source code delivery
  • Option to re-start a closed venture

See how we can unwrap your app idea and proceed towards success