How to add Firebase services to your React Native project

Subscribe to my newsletter and never miss my upcoming articles

Today I will walk you through the basic steps of adding Firebase services to your React Native project

The steps are simple:

  1. Add Firebase NPM packages
  2. Initialize Firebase
  3. Import when needed

First step: Adding Firebase NPM package

First, go to your project folder. If you have not made a React Native project yet, you can do so with Expo-CLI or React-Native-CLI

For those who already have a React Native project running, please forward to Step 2

# Install the Expo CLI
npm install --global expo-cli

# After that, initialize the project
expo init my-app

# Navigate to the project folder
cd my-app

Screen Shot 2021-02-27 at 10.37.02 PM.png

You can choose a Blank project for starter

After you have initialize the project, go ahead and add Firebase NPM package

#Add Firebase NPM package
sudo expo install firebase

Step 2: Initialize Firebase

Onto the next step, we are going to install Firebase CLI and Initialize Firebase in our project

# Install Firebase CLI
npm install -g firebase-tools

# Initialize Firebase in project
firebase init

# Additionally you might need to login
firebase login

Screen Shot 2021-02-27 at 10.50.27 PM.png

Follow the instruction to add the services that you want to use

Screen Shot 2021-02-27 at 10.51.03 PM.png

Choose the Firebase project that you want to work on

Step 3: Import Firebase services

Import Firebase and initialize it where you need

import { StatusBar } from 'expo-status-bar';
import React, {useEffect} from 'react';
import { StyleSheet, Text, View } from 'react-native';

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore"

Then initialize Firebase

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore"


if (!firebase.apps.length) {
  firebase.initializeApp({
    apiKey: "yourKey",
    authDomain: "yourDomain",
    projectId: "yours",
    storageBucket: "yours",
    messagingSenderId: "yours",
    appId: "yours",
    measurementId: "yours",
  });
} else {
  firebase.app();
}

You can find all the keys under Firebase > Project Settings

Attention: Common Error

Make sure to call any Firebase services (Firestore, Auth, etc) after Firebase init. The safe place to call them is inside the App/ Component function

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore"

//not here
const firestore = firebase.firestore()
const auth = firebase.auth()

function HomeScreen(){
//here
const firestore = firebase.firestore()
const auth = firebase.auth()
...
}

}

That is it!

Enjoy your Firebase services, you can learn how to setup Firestore and other stuff here.

No Comments Yet