Firebase Realtime Database integration with React Native

Pradeep Sharma
4 min readAug 5, 2022

In this post, we’ll learn how to integrate Realtime Database in React Native apps using Firebase. and perform CRUD (Create Read Update Delete ) operations on a real-time Database in Android.

for the integration of the firebase, we need to follow some steps:

  1. Integrate firebase in Your React native Project [you can follow my blog for it here]
  2. Installing Dependencies for the Realtime Database
  3. CRUD Operations
  • Reading Data
  • Writing Data
  • Updating Data
  • Deleting Data

Step 1st is done by the link which I have provided so here we follow Step 2

Step 2. Installing dependencies for the real-time database

This module requires that the @react-native-firebase/app module is already set up and installed. To install the "app" module, view the blog.

# Install & setup the app module
yarn add @react-native-firebase/app
# Install the database module
yarn add @react-native-firebase/database
# If you're developing your app using iOS, run this command
cd ios/ && pod install && cd ..

if you are using an older version of react native without auto-linking you can follow this guide here for android and for iOS

A core concept to understanding Realtime Database are references — a reference to a specific node within your database. A node can be a specific property or sub-nodes.

To create a Reference, call the ref method:

import database from '@react-native-firebase/database';const reference = database().ref('/users/123');

NOTE: To get a reference to a database other than an ‘us-central1’ default database, you must pass the database URL. You can find your Realtime Database URL in the Realtime Database section of the Firebase console.

import { firebase } from '@react-native-firebase/database';const reference = firebase
.app()
.database('https://<databaseName>.<region>.firebasedatabase.app/')
.ref('/users/123');

3. CRUD Operations

1. Reading data

The Realtime Data provides the ability to read the value of a reference as a one-time read, or real-time changes to the node. When a value is read from the database, the API returns a DataSnapshot.

  • One-time read

To read the value once, call the once method on a reference:

import database from '@react-native-firebase/database';database()
.ref('/users/123')
.once('value')
.then(snapshot => {
console.log('User data: ', snapshot.val());
});
  • Realtime changes

To set up an active listener to react to any changes to the node and its children, call the on method with an event handler:

import database from '@react-native-firebase/database';database()
.ref('/users/123')
.on('value', snapshot => {
console.log('User data: ', snapshot.val());
});

The event handler will be called straight away with the snapshot data, and further called when any changes to the node occur.

You can unsubscribe from events by calling the off method. To unsubscribe from specific events, call the off method with the function that the event handler returned. This can be used within any useEffect hooks to automatically unsubscribe when the hook needs to unsubscribe itself:

import React, { useEffect } from 'react';
import database from '@react-native-firebase/database';
function User({ userId }) {
useEffect(() => {
const onValueChange = database()
.ref(`/users/${userId}`)
.on('value', snapshot => {
console.log('User data: ', snapshot.val());
});
// Stop listening for updates when no longer required
return () => database().ref(`/users/${userId}`).off('value', onValueChange);
}, [userId]);
}
  • Additional events

The above example demonstrates how to subscribe to events whenever a value within the node changes. In some cases, you may need to only subscribe to events whenever a child node is added/changed/moved/removed. This can be achieved by passing a different EventType to the on method.

If you are listening to a node with many children, only listening to data you care about helps reduce network bandwidth and speeds up your application.

import React, { useEffect } from 'react';
import database from '@react-native-firebase/database';
function User({ userId }) {
useEffect(() => {
const onChildAdd = database()
.ref('/users')
.on('child_added', snapshot => {
console.log('A new node has been added', snapshot.val());
});
// Stop listening for updates when no longer required
return () => database().ref('/users').off('child_added', onChildAdd);
}, [userId]);
}

2. Writing data

The Firebase documentation provides great examples of best practices on how to structure your data. highly recommend reading the guide before building out your database.

  • Setting data

The set method on a Reference overwrites all of the existing data at that reference node. The value can be anything; a string, number, object etc:

import database from '@react-native-firebase/database';database()
.ref('/users/123')
.set({
name: 'Ada Lovelace',
age: 31,
})
.then(() => console.log('Data set.'));

If you set the value to null, Firebase will automatically class the node as removed and delete it from the database.

3. Updating data

Rather than overwriting all existing data, the update method provides the ability to update any existing data on the reference node. Firebase will automatically merge the data depending on what currently exists.

import database from '@react-native-firebase/database';database()
.ref('/users/123')
.update({
age: 32,
})
.then(() => console.log('Data updated.'));
  • Pushing data

Currently, the examples have only demonstrated working with known reference node keys (e.g. /users/123). In some cases, you may not have a suitable id or may want Firebase to automatically create a node with a generated key. The push method returns a ThenableReference, allowing you to observe a node before it is sent to the remote Firebase database.

The push method will automatically generate a new key if one is not provided:

const newReference = database().ref('/users').push();console.log('Auto generated key: ', newReference.key);newReference
.set({
age: 32,
})
.then(() => console.log('Data updated.'));

The keys generated are ordered to the current time, so the list of items returned from Firebase will be chronologically sorted by default.

4. Deleting data

To remove data, you can call the remove method on a reference:

await database().ref('/users/123').remove();

Optionally, you can also set the value of a reference node to null to remove it from the database:

await database().ref('/users/123').set(null);

hope this article is useful for you!🙂🙂

If you enjoyed this article, share it with your friends and colleagues!😇

--

--