Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

Consume Data from Firebase Firestore in a React App

Gaurav Singhal

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

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.

1body: "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."
2created_at: November 11, 2020 at 12:00:00 AM UTC+5:30
3posted_by: "Sam"
4title: "New Egg Recipe"
json

Now head over to your React app and install Firebase.

1npm 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.

1import firebase from 'firebase'
2var firebaseConfig = {
3    apiKey: "xxxxxxxxxxxxxxxx",
4    authDomain: "xxxxxxxxxxxxxxxx",
5    databaseURL: "xxxxxxxxxxxxxxxx",
6    projectId: "xxxxxxxxxxxxxxxx",
7    storageBucket: "xxxxxxxxxxxxxxxx",
8    messagingSenderId: "xxxxxxxxxxxxxxxx",
9    appId: "xxxxxxxxxxxxxxxx",
10    measurementId: "xxxxxxxxxxxxxxxx"
11  };
12  
13const firebaseApp=firebase.initializeApp(firebaseConfig);
14const db=firebase.firestore();
15
16export 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.

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

Create a piece of state to store your data.

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

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

1  useEffect(() => {
2    fetchBlogs();
3  }, [])
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.

1const fetchBlogs=async()=>{
2    const response=db.collection('Blogs');
3}
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.

1const fetchBlogs=async()=>{
2    const response=db.collection('Blogs');
3    const data=await response.get();
4}
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.

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

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

Final Code

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

1import './App.css';
2import db from './firebase.config';
3import React,{useState,useEffect} from 'react';
4
5function App() {
6  const [blogs,setBlogs]=useState([])
7  const fetchBlogs=async()=>{
8    const response=db.collection('Blogs');
9    const data=await response.get();
10    data.docs.forEach(item=>{
11     setBlogs([...blogs,item.data()])
12    })
13  }
14  useEffect(() => {
15    fetchBlogs();
16  }, [])
17  return (
18    <div className="App">
19      {
20        blogs && blogs.map(blog=>{
21          return(
22            <div className="blog-container">
23              <h4>{blog.title}</h4>
24              <p>{blog.body}</p>
25            </div>
26          )
27        })
28      }
29    </div>
30  );
31}
32
33export 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 .