Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Consume Data from Firebase Firestore in a React App

Firebase serves as an entire backend as a service by providing authentication, cloud functions, real-time database, Cloud Firestore, and more.

Nov 16, 2020 • 7 Minute Read

Introduction

Firebase allows you to build serverless web apps easily by giving you numerous features right out of the box. It serves as an entire backend as a service by providing authentication, cloud functions, real-time database, Cloud Firestore, and more.

In this guide, you'll learn how to consume data from Firebase Cloud Firestore in your React app.

Initial Setup

Ensure that you have an account on firebase.google.com and create a new Firebase project. Click on Add Firebase to Your Web App and follow the steps. Head over to the Cloud Firestore section and create a new collection called Blogs. Add a document as shown below.

      body: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
created_at: November 11, 2020 at 12:00:00 AM UTC+5:30
posted_by: "Sam"
title: "New Egg Recipe"
    

Now head over to your React app and install Firebase.

      npm i firebase
    

Create a new file called firebase.config.js to store all configurational details required to connect to your Firebase project. Head over to your project settings and copy the firebaseConfig and paste it inside the firebase.config.js file.

      import firebase from 'firebase'
var firebaseConfig = {
    apiKey: "xxxxxxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxxxxxx",
    messagingSenderId: "xxxxxxxxxxxxxxxx",
    appId: "xxxxxxxxxxxxxxxx",
    measurementId: "xxxxxxxxxxxxxxxx"
  };
  
const firebaseApp=firebase.initializeApp(firebaseConfig);
const db=firebase.firestore();

export default db;
    

Make sure you have correctly added your own Firebase project's firebaseConfig. Initialize the Firebase app by passing in the firebaseConfig to firebase.initializeApp() method and get a reference to the database by calling the firestore() method on the Firebase object and storing it in a variable.

Consuming Data from Firestore

Consuming data from Firestore is similar to consuming JSON data from a REST API. First, import db from the config file along with useState and useEffect to create state, and fire the request to fetch data.

      import db from './firebase.config';
import React,{useState,useEffect} from 'react';
    

Create a piece of state to store your data.

      const [blogs,setBlogs]=useState([])
    

Create an async function to fetch data from Firestore and call it inside useEffect, as shown below.

      useEffect(() => {
    fetchBlogs();
  }, [])
    

Inside the fetchBlogs() method, get a reference to your database by calling the collection() method on the db object and passing in the name of the collection as a parameter.

      const fetchBlogs=async()=>{
    const response=db.collection('Blogs');
}
    

In order to get the data from this response object, using the await keyword, call the get() method on the response object and store it inside a variable data.

      const fetchBlogs=async()=>{
    const response=db.collection('Blogs');
    const data=await response.get();
}
    

The data object contains a property called docs that contains information about each individual document in the collection. Thus each document could contain information about an individual blog. Iterate over data.docs to get an individual item and call the data() method on each item to get the data inside it.

      const fetchBlogs=async()=>{
    const response=db.collection('Blogs');
    const data=await response.get();
    data.docs.forEach(item=>{
     setBlogs([...blogs,item.data()])
    })
}
    

You can add the data to your state as shown above inside the loop. Since the Blogs collection consists of a single document, your state will also contain a single item. Finally, cycle through your state and render the data on the DOM.

      return (
    <div className="App">
      {
        blogs && blogs.map(blog=>{
          return(
            <div className="blog-container">
              <h4>{blog.title}</h4>
              <p>{blog.body}</p>
            </div>
          )
        })
      }
    </div>
  );
    

Final Code

Have a look at the entire code that consumes data from a Firestore collection below.

      import './App.css';
import db from './firebase.config';
import React,{useState,useEffect} from 'react';

function App() {
  const [blogs,setBlogs]=useState([])
  const fetchBlogs=async()=>{
    const response=db.collection('Blogs');
    const data=await response.get();
    data.docs.forEach(item=>{
     setBlogs([...blogs,item.data()])
    })
  }
  useEffect(() => {
    fetchBlogs();
  }, [])
  return (
    <div className="App">
      {
        blogs && blogs.map(blog=>{
          return(
            <div className="blog-container">
              <h4>{blog.title}</h4>
              <p>{blog.body}</p>
            </div>
          )
        })
      }
    </div>
  );
}

export default App;
    

Conclusion

You can not only consume data but also add data to Firebase collections. You can also make complex structures by nesting collections depending on the complexity of the database you want to have. Using React with Firebase can help you develop both prototypes as well as production-based apps in no time without any complicated server setup. You can explore more features of Firebase by reading the official documentation.

If you have any questions, feel free to reach out to me at Codealphabet .