React and Firestore Part 1
Tags: react, javascript, webdev, firebase
Published: 2023-03-20 11:25:54

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](https://turbofuture.com/computers/React-and-Firebase-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](https://turbofuture.com/computers/React-and-Firebase-A-complete-tutorial-Part-1).

## 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:

```javascript
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;
```

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.

```javascript
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;
```

### 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.

```javascript
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;
```

---

Thanks for Reading!

> Check out my [blog](https://saleh.hashnode.dev) too!

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

<a href="https://www.buymeacoffee.com/salehmubashar" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-violet.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>