Skip to main content

React and Firestore: A Complete Tutorial—Part 1

Saleh is an experienced Web Developer and uses his knowledge and experience to guide people looking to learn Web Dev and new technologies

react-and-firebase-a-complete-tutorial-part-1

In this tutorial, we will learn how to save and get data from Firestore, which is a cloud-hosted, Firebase NoSQL database. We will be saving and retrieving data from this database using React JS.

Creating the Firestore Database

Firstly we need to create a new Firebase app and a Firestore database. Go to https://firebase.google.com/ and click on Get Started. Next, click on add a project and fill out the required details.

You may be asked to enable Google Analytics at some point. There’s no need for it for this tutorial, so feel free to skip that step.

Create a Project

Create a Project

Inside your React app next to your App,js file, create a file called firebase.js. This will contain our Api keys and credentials.

Integrating Firebase Into Our React App

Next up, we need get the web configuration object from firebase. Go to your Firebase console and create a new web app by clicking on the </> option.

Create a new Web App

Create a new Web App

Fill in the required details and then click on Register App. You will then be given the firebaseconfig object. Copy this data, we will use it in our firebase.js file.

SDK

SDK

Next up, install Firebase in your React app using the following npm command:

npm i firebase

Next, in your firebase.js file, add the following code:

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "AUTH_DOMAIN",
  projectId: "PROJECT_ID",
  storageBucket: "STORAGE_BUCKET",
  messagingSenderId: "MESSAGING_SENDER_ID",
  appId: "APP_ID"
}

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
  
export default db;

In the above code, replace the config object with the one you copied earlier. In this file, we are basically initializing Firebase and the Firestore database.

Create the Firestore Database

Back to your Firebase console, create a new Firestore database.

Scroll to Continue
Create the firestore database

Create the firestore database

Next, create a new collection. You can call this whatever you want. Let's call it "users" for now. Next create a simple test document. This is basically a piece of data (an individual user in our case). We can set this using React later too.

Next, change the permissions to allow Read and Write so that we can work with the app on localhost.

Adding Data to Firestore

Now we will see how to add data to our firestore database. Firstly in your React file, lets say App.js, import the database from the firebase.js file. Next, get the collection "users" and then create a new doc. This new doc can be the user name or a random id etc.

In our case we will create a new doc called user1 and add the first name of the user to it like this:

import * as React from "react";
import db from "./firebase";

function App() {
  const getData = async () => {
    await db
      .collection("users")
      .doc("user1")
      .set({ username: "John" });
  };
  getData();
  return <div className="app"></div>;
}

export default App;

All we are doing here is creating a new doc called user1 inside the "users" collection and adding some data to it.

getData() is an async and await function. The async and await keywords enable asynchronous, promise-based behaviour. When we run this function and save the file, the data will be added to the database.

Note: the doc name should be unique, so we can not create another document with the name user1.

Fire store Database

Fire store Database

Getting Data From Firestore

There are two main ways of achieving this:

  1. Call a method to get the data.
  2. Set a listener to receive data-change events

Let's look at both of these methods:

Method 1: Getting Documents

In this method, we simply get a specific document or multiple documents from a collection using the get() function. This retrieves the data once, meaning it is not Realtime. If there is a change to the database, you will need to refresh the page to see them.

We will again use an async await function here and use the get() function to get all the docs from the "users" collection. The get() function returns an object, and we can loop over it and get get the data using the data() function followed by the item name.

import * as React from "react";
import db from "./firebase";

function App() {
  const getData = async () => {
    const docs = await db.collection("users").get();
    docs.forEach((doc) => {
      console.log(doc.data().username);
    });
  };
  getData();
  return <div className="app"></div>;
}

export default App;

As you can see above, we are first all the docs from the users collection. Then we are looping over the object to get the username from each doc with the help of the data() function.

This will return the usernames of all the documents inside the "users" function.

We can also get a single document for example user1 like such. In this case, there will be no need of using a forEach function:

import * as React from "react";
import db from "./firebase";

function App() {
  const getData = async () => {
    const doc = await db
      .collection("users")
      .doc("user1")
      .get();
    console.log(doc.data().username);
  };
  getData();
  return <div className="app"></div>;
}

export default App;

Method 2: Snapshots

You can listen to a document with the onSnapshot() method. When a document is updated, then another call updates the document snapshot. This means that the data is automatically updated and displayed the users without the need to refresh the page.

Basically, we will use the onSnapshot function on the users collection. Each of the snapshots received will contain an array of documents that we can loop over like earlier.

import * as React from "react";
import db from "./firebase";

function App() {
  const getData = async () => {
    const collection = db.collection("users");
    collection.onSnapshot((querySnapShot) =>{
      querySnapShot.forEach((doc) =>{
        console.log(doc.data().username)
      })
    })
  };
  getData();
  return <div className="app"></div>;
}

export default App;

Conclusion

There you have it!

Hope you enjoyed this tutorial. In the next part will discuss how to update, delete and sort data.

Thanks!

This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.

Related Articles