Expo React Native Retrieve Data from Firebase Tutorial

React Native fetch firebase data collection tutorial; In this comprehensive guide, you will learn how to retrieve data from firestore in React Native application using the Firestore real-time database.

To Retrieve data from Firestore in react native, we will show you how to create a Firebase account and create a new firebase project. Also, show you how to set up Firebase in expo react native application using the Firebase JavaScript SDP offered by Firebase.

At the end of this tutorial, you will know how easy it is to get data from Firebase in React Native apps with Firestore.

How to Get Data From Firebase in React Native

  • Step 1: Install Expo CLI
  • Step 2: Create Expo React Native App
  • Step 3: Create Firebase Project
  • Step 4: Set Up Firebase in React Native
  • Step 5: Install React Native Elements Package
  • Step 6: Fetch Data
  • Step 7: Add Component in App Js
  • Step 8: Run App on Device

Install Expo CLI

You have to install Node 12 LTS or greater version in your development system; you can either use npm or yarn to begin installing the Expo CLI.

# npm
npm install -g expo-cli

# yarn
yarn global add expo-cli

Create Expo React Native App

Right after that, execute the given command to download the new React Native application.

expo init RnBlogProject

Now, the project is ready, next, dive into the app folder.

cd RnBlogProject

Create Firebase Project

Go to firebase.google.com site, create a new firebase project for react native.

Firebase Create Account

Give a name to your firebase project.

Create a project

Next, click on the web icon to get started by adding Firebase to your app.

add Firebase to app

Include Firebase to your web app, register the app and add firebase to your web app; you can also configure Firebase Hosting by selecting on the checkbox.

add firebase

Now, copy the Firebase SDK you will need it to connect react native app to Firebase.

Firebase configuration keys

Set Up Firebase in React Native

This expo react native app requires firebase expo package to be installed in react native app.

expo install firebase

Expos app requires the dotenv package, so use command to install the package.

npm install dotenv

Now, create the .env file at the root of your react native app. Then, replace the firebase credentials with the *, make sure to create this file .

  apiKey: "****************************",
  authDomain: "****************************",
  projectId: "****************************",
  storageBucket: "****************************",
  messagingSenderId: "****************************",
  appId: "****************************"

Look for the app.json file, change the name to app.config.js, you have to update the suggested code within the file.

import 'dotenv/config';

export default {
  expo: {
    name: 'RnBlog',
    slug: 'RnBlog',
    version: '1.0.0',
    orientation: 'portrait',
    icon: './assets/icon.png',
    splash: {
      image: './assets/splash.png',
      resizeMode: 'contain',
      backgroundColor: '#ffffff'
    },
    updates: {
      fallbackToCacheTimeout: 0
    },
    assetBundlePatterns: ['**/*'],
    ios: {
      supportsTablet: true
    },
    android: {
      adaptiveIcon: {
        foregroundImage: './assets/adaptive-icon.png',
        backgroundColor: '#FFFFFF'
      }
    },
    web: {
      favicon: './assets/favicon.png'
    },
    extra: {
      apiKey: process.env.apiKey,
      authDomain: process.env.authDomain,
      projectId: process.env.projectId,
      storageBucket: process.env.storageBucket,
      messagingSenderId: process.env.messagingSenderId,
      appId: process.env.appId
    }
  }
};

Next, create the config directory, within this folder, create the firebase.js file and add the following code.

import * as firebase from 'firebase';
import firestore from 'firebase/firestore';

const firebaseConfig = {
  apiKey: "****************************",
  authDomain: "****************************",
  projectId: "****************************",
  storageBucket: "****************************",
  messagingSenderId: "****************************",
  appId: "****************************"
};

firebase.initializeApp(firebaseConfig);

firebase.firestore();

export default firebase;

Next, you have to visit the Firebase database and click on the Firestore Database; in the Cloud Firestore dashboard, you need to create the students’ collection and add some data to show as the list with name and designation properties.

Install React Native Elements Package

In this step, you have to type the command on the console and hit enter to install the react native elements package.

npm install react-native-elements

Fetch Data

In this step, we will show you how to fetch data from the firestore database, also learn how to use ListItems to create rows of data and at the same to display firebase data in react native app.

Create components/ folder, inside this folder create fetchlist_screen.js file and insert the entire below code.

import React, { Component } from 'react';

import { StyleSheet, ScrollView, ActivityIndicator, View } from 'react-native';
import { ListItem } from 'react-native-elements';
import firebase from '../config/firebase';


class FetchListScreen extends Component {

    constructor() {
        super();
        this.docs = firebase.firestore().collection('students');
        this.state = {
          isLoading: true,
          students: []
        };
      }
    
      componentDidMount() {
        this.unsubscribe = this.docs.onSnapshot(this.getStudentsData);
      }
    
      componentWillUnmount(){
        this.unsubscribe();
      }
    
      getStudentsData = (querySnapshot) => {
        const students = [];
        querySnapshot.forEach((res) => {
          const { name, designation } = res.data();
          students.push({
            key: res.id,
            name,
            designation
          });
        });
        this.setState({
          students,
          isLoading: false
       });
      }
    
    
    
      render() {
        if(this.state.isLoading){
          return(
            <View style={styles.loader}>
              <ActivityIndicator size="large" color="red"/>
            </View>
          )
        }    
        return (
          <ScrollView style={styles.wrapper}>
              {
                this.state.students.map((res, i) => {
                  return (
                    <ListItem 
                       key={i}           
                       bottomDivider>
                      <ListItem.Content>
                        <ListItem.Title>{res.name}</ListItem.Title>
                        <ListItem.Subtitle>{res.designation}</ListItem.Subtitle>
                      </ListItem.Content>
                      <ListItem.Chevron 
                         color="black" 
                      />
                    </ListItem>
                  );
                })
              }
          </ScrollView>
        );
      }
    }
    
    const styles = StyleSheet.create({
      wrapper: {
       flex: 1,
       paddingBottom: 22
      },
      loader: {
        position: 'absolute',
        alignItems: 'center',
        justifyContent: 'center',    
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
      }
    })

export default FetchListScreen;

Add Component in App Js

Now, move to the App.js file and register the newly created component in this file.

import React from 'react';
import FetchListScreen from './components/fetchlist_screen.js'

export default function App() {
  return (
    <FetchListScreen/>
  );
}

Run App on Device

Now, we need to check the app on the smartphone; You have to install the Expo Client on your smartphone. You can download the expo from Google Play Store or App Store.

# npm
npm start

# yarn
yarn start

Scan the QR code appeared on your browser or console screen using the expo app.

Make sure your development machine and smartphone are on the same network.

Expo React Native Retrieve Data from Firebase Tutorial

Summary

Expo offers robust support for React Native and Firebase, which works best on react native and firebase. Be it Firestore and real-time databases, storage, functions, or authentication services of Firebase. In this tutorial, we shed light only on the iota of Firebase and React Native; you have learned how to get data from Firestore and show it on the React native app using expo cli.