Skip to main content

React and Firestore: A Complete Tutorial—Part 2

react-and-firestore-a-complete-tutorialpart-2

In the previous tutorial, Part 1, we learned how to save and get data from Firestore, which is a cloud-hosted, Firebase NoSQL database. We also learned how to create and integrate a Firestore database to React.

In Part 2, we will learn how to update, delete and sort data.

Updating Documents in Firestore

We may be necessary to update a document when we need to change data without overwriting the whole document.

First, in your React file, let's say App.js, import the database from the firebase.js file. Next, get the collection "users" and check whether the document you want to update exists or not.

In this case, we have a single document in our users database. We will check if this document exists.

Database View

Database View

import React from "react";
import db from "./firebase";
function App() {
  const getData = async () => {
    //get the user
    const user = db.collection("users").doc("user1");
    const doc = await user.get()
    //check if user exists
    if (doc.exists) {
      console.log("User Exists!");
    } else {
      console.log("User does not exist!");
    }
  };
  getData();

  return <div className="app"></div>;
}
export default App;

Here, we are basically creating a simple async function that gets the user document from the user's database and checks if it exists or not.

Now, we can update this user if it exists by using the update method. We will provide it an object that will contain the name attribute and its updated value.

import React from "react";
import db from "./firebase";
function App() {
  const getData = async () => {
    //get the user
    const user = db.collection("users").doc("user1");
    const doc = await user.get();
    //check if user exists
    if (doc.exists) {
      //if user exists, update the name
      await user.update({ username: "Mike" });
    } else {
      console.log("User does not exist!");
    }
  };
  getData();

  return <div className="app"></div>;
}
export default App;
Updated Database View

Updated Database View

As you can see in the screenshot, the username of user1 has been changed from John to Mike.

Deleting Documents in Firestore

Once again, we will check if the document exists in the first place. If it does, we will delete the document using the simple delete method.

import React from "react";
import db from "./firebase";
function App() {
  const getData = async () => {
    //get the user
    const user = db.collection("users").doc("user1");
    const doc = await user.get();
    //check if user exists
    if (doc.exists) {
      //if user exists we delete it
      await user.delete()
    } else {
      console.log("User does not exist!");
    }
  };
  getData();

  return <div className="app"></div>;
}
export default App;

Sort Data From Firestore

Getting a List of Documents

Let's discuss how to sort the data we retrieve from Firestore. First, we need to get all the documents in the database and display the data as a list. For this, let's first create a few users in the database.

New Documents Added

New Documents Added

As you can see, we have created three documents. Now we will retrieve them and display them in our app. For this, we will first get all the documents in a snapshot.

Next, we will map through them and display them as a list in the console.

import React from "react";
import db from "./firebase";
function App() {
  const getData = async () => {
    //get the users
    const users = await db.collection("users").get();
    // display each user
    users.docs.forEach((doc)=>{
      console.log(doc.data().username)
    })
  };
  getData();
  return <div className="app"></div>;
}
export default App;
react-and-firestore-a-complete-tutorialpart-2

As you can see, all three users are dispalyed. Now we need to sort them alphabetically. To do this, we can use the orderBy method directly on the users collection before getting them.

We will provide it two parameters:

  1. The attribute by which we need to sort
  2. We will tell determine whether it has to be ascending or descending (ascending will be A-Z order in this case)
import React from "react";
import db from "./firebase";
function App() {
  const getData = async () => {
    //get the users
    const users = await db.collection("users").orderBy("username", "asc").get();
    // display each user
    users.docs.forEach((doc) => {
      console.log(doc.data().username);
    });
  };
  getData();
  return <div className="app"></div>;
}
export default App;
react-and-firestore-a-complete-tutorialpart-2

As you can see, the data is ordered alphabetically A-Z.

That will be all for this tutorial series. Thanks for sticking around!

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.

© 2022 Saleh Mubashar