Author avatar

Gaurav Singhal

Consume Data from Firebase Firestore in a React App

Gaurav Singhal

  • Nov 16, 2020
  • 7 Min read
  • 80 Views
  • Nov 16, 2020
  • 7 Min read
  • 80 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

1
2
3
4
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"
json

Now head over to your React app and install Firebase.

1
npm i firebase
shell

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
javascript

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.

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

Create a piece of state to store your data.

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

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

1
2
3
  useEffect(() => {
    fetchBlogs();
  }, [])
javascript

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.

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

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.

1
2
3
4
const fetchBlogs=async()=>{
    const response=db.collection('Blogs');
    const data=await response.get();
}
javascript

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.

1
2
3
4
5
6
7
const fetchBlogs=async()=>{
    const response=db.collection('Blogs');
    const data=await response.get();
    data.docs.forEach(item=>{
     setBlogs([...blogs,item.data()])
    })
}
javascript

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
return (
    <div className="App">
      {
        blogs && blogs.map(blog=>{
          return(
            <div className="blog-container">
              <h4>{blog.title}</h4>
              <p>{blog.body}</p>
            </div>
          )
        })
      }
    </div>
  );
jsx

Final Code

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
jsx

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 .

2