DEV Community

Cover image for React and Firestore Part 1
Saleh Mubashar
Saleh Mubashar

Posted on • Updated on

React and Firestore Part 1

Hi guys!

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.

You can read the detailed version of this article here:

React and Firestore: A complete tutorial - Part 1


We will discuss how to save and retrieve data from the firestore database. Creation and setup of the database is discussed in the detailed version.

Adding Data to Firestore

Nn your React file, let's say App.js, import the database from the firebase.js file (contains the credentials of the database). Next, get the collection "users" (for example) 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 setData = async () => {
    await db
      .collection("users")
      .doc("user1")
      .set({ username: "John" });
  };
  setData();
  return <div className="app"></div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

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

setData() 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.

Getting Data From Firestore

There are two main ways of achieving this:

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 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;
Enter fullscreen mode Exit fullscreen mode

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 to 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;
Enter fullscreen mode Exit fullscreen mode

Thanks for Reading!

Check out my blog too!

If you learnt something new, you can buy me a coffee to support my work!
Cheers :)

Buy Me A Coffee

Top comments (0)