How To Integrate Firebase Cloud Firestore Database with React Native App

In this tutorial, we are going to learn step by step guide “How To Integrate Firebase Cloud Firestore Database with React Native App”. We are also implementing the Firestore cloud with a simple React Native app.

In this sample react native app we are trying to cover the complete CRUD operation, so you understand the complete flow, let’s start.

react native

Introduction of Firebase Firestore –

Firebase Firestore is a NoSQL cloud database that helps you easily sync and store data for your mobile and web apps. with the help of Firestore, you can automatically synchronize your app data between multiple devices.

It also offers you offline support so you can create responsive apps that work regardless of network and Internet connectivity.

Following are some pros of using Firestore as your database.

    • Firebase Cloud Firestore is a flexible, scalable database for mobile, server, and web development.
    • Firestore keeps your data in sync across all client apps through realtime listeners and offline support.
    • With the help of Firebase Firestore, you can build responsive apps that work smoothly on the web and mobile.
    • Firestore also offers seamless integration with other Firebase and Google Cloud products.

Benefits of using Google Firebase Cloud Firestore –

    • Benefits of Firebase with Google Cloud Platform
    • Cloud/Serverless Solution
    • Excellent Data Handling Capabilities
    • Designed to Scale
    • Promises Robust Security
    • Enables Offline Support
    • Cost-Effective Pricing

Data Structure For Firestore – 

We all know that NoSQL is storing data in document format, so like all other NoSQL databases Cloud Firestore also stores data within “documents”.

Firstly we discussed documents, documents simply contain the data in key values, and Documents are stored within collections.

A document can contain another collection to the dictionary of key values. 

react native firestore

Break down the implementation steps –

  1. Create an account in Firebase
  2. Create a React native app
  3. Register your app with Firebase
  4. Install and setup the required npm module (we have done this in the implementation steps)
  5. Implement the Firestore (we have done this in the implementation steps)
  6. Run the app

So let’s start integrating the app steps.

Step 1 & Step 3 – Create an account in Firebase & Register your app with Firebase

For creating an account with Firebase and registering your app, please follow this tutorial, here I already do the setup.

1. FIREBASE SETUP,

2. FIREBASE WITH ANDROID STUDIO,

3. FIREBASE PLUGIN

Step 2 – Create a React native app

Firstly we need to create a React native app for implementing Firestore.

Run the following commands to create a new React Native project

react-native init firestoreDemo

Step 6 – Run the app

react-native run-android

Now we are going to create a Firestore database in Firebase. follow these steps for creating Firestore.

  1. Next, click on the “Develop > Database” menu.
firestore
  1. Here, we have to create a Cloud Firestore database so click on the “Create database” button.
  1. For development purposes, we are setting up the security rules for Cloud Firestore in test mode.
 firebase firestore
itechinsiders react firebase firestore

4. Next, create a collection in Cloud Firestore. Let’s create a ‘users’ collection with name, email, and mobile values.

itechinsiders react native firestore
itechinsiders firebase firestore
react native firebase firestore

Now we are going to perform the CRUD operation in our app. We have to perform this action also in steps so follow it carefully.

Firestore Database Implementation With React Native –

Step 1 – Install and setup the required npm module

Here we have to install the all required Firebase npm lib for running Firestore.

Run the following commands to install the Firebase and Firestore.

With yarn -
yarn add @react-native-firebase/app
yarn add @react-native-firebase/firestore
cd ios/ && pod install

with npm -
npm i @react-native-firebase/app
npm i @react-native-firebase/firestore
cd ios/ && pod install

For more details check this link.

Step 2 – Getting Collection Ref in the app

Here we get the collection of users which we created on firebase cloud firestore for our app.

import the lib - 
import firestore from '@react-native-firebase/firestore';

access the collection on componentDidMount - 
const usersCollection = firestore().collection('users');

It returns a collection reference which is used to fetch the query data.

  • We can use the get method to get the current snapshot of the collection.
async componentDidMount() {
    try {
        firestore()
          .collection('users')
          .get()
          .then(querySnapshot => {
            if (querySnapshot?._docs?.length > 0) {
             //put your navigation file 
              navigation.navigate('Password');
            } else {
             //put your navigation file 
                navigation.navigate('AppIntroSliders');
            }
          });
    } catch (error) {
       //put your navigation file 
        navigation.navigate('AppIntroSliders');
    }
  }
  • You can use the get with-where condition method to get the current snapshot of the collection.
async componentDidMount() {
    let {navigation} = this.props;
    await DeviceInfo.getUniqueId().then(uniqueId => {
      this.setState({deviceID: uniqueId});
    });
    try {
        firestore()
          .collection('Users')
          .where('deviceID', '==',deviceID)//use your cond
          .get()
          .then(querySnapshot => {
         console.log('querySnapshot',querySnapshot?._docs)
         }
    } catch (error) {                   console.log('error',error)
    }
  }

Step 3: How to Get a Single Document Ref in the app with Firestore

When you create a user collection then within it we create multiple docs, so if you want to get information on any particular doc then use the below code.

import firestore from '@react-native-firebase/firestore';
const userDocument = firestore()
    .collection('users')
    .doc('3ae76e95-5112-4b55-8878-e7c29dd300aa');

getting current snapshot - 

const userDocument = firestore()
    .collection('Users')
    .doc('3ae76e95-5112-4b55-8878-e7c29dd300aa')
    .then(docSnapshot => {
        if (docSnapshot.exists) {
            const userData = docSnapshot.data()
            console.log(userData)
        }
    });

Step 4: How to Add a New Document to a Firestore Collection

Once you have a collection reference, you can use it to add documents to that collection.

import firestore from '@react-native-firebase/firestore';
firestore()
    .collection('Users')
    .add({
        name: 'test',
        mobile: '1234567890',
        email:'test@gmail.com'
    })
    .then(() => {
        console.log('User added!');
    });

By using the Firestore method add, it will automatically set a random unique ID to each doc. If you want to set any specific doc ID like device id etc then you can use the set method instead.

firestore()
    .collection('Users')
    .doc('4bd047de-eb21-4dc0-bca9-2d3d0c5b7acd')
    .set({
        name: 'test',
        mobile: '1234567890',
        email:'test@gmail.com'
    })
    .then(() => {
        console.log('User added!');
    });

Step 4: How to Update an existing document in Firestore

Updating a document is very easy. Instead of using the set method, you can use the update method.

import firestore from '@react-native-firebase/firestore';
firestore()
    .collection('Users')
    .doc('4bd047de-eb21-4dc0-bca9-2d3d0c5b7acd')
    .update({
        name: 'test123',
        mobile: '1234567890',
        email:'test@gmail.com'
    })
    .then(() => {
        console.log('User added!');
    });

Step 5: How to Delete a Document in Firestore

Firestore provides a delete method that can be used to delete an existing document.

import firestore from '@react-native-firebase/firestore';
firestore()
    .collection('Users')
    .doc('4bd047de-eb21-4dc0-bca9-2d3d0c5b7acd')
    .delete()
    .then(() => {
        console.log('User added!');
    });

So we completed the react-native Firebase Cloud Firestore Database which is “How To Integrate Firebase Cloud Firestore Database with React Native App

Here You find my next post here.

Here is my B2B startup app link – https://play.google.com/store/apps/details?id=com.beparr.buyer

My website for B2B – https://www.beparr.com/

In conclusion, If have any queries or issues, please feel free to ask.

Happy Coding Guys.

Related Post