Design+Code logo

Quick links

Suggested search

CodeSandbox link

You can find the full code for this tutorial at https://codesandbox.io/s/firestore-lbiog.

Set up Firebase

Make sure that you have Firebase set up in your React project. If you haven't, you can set it up by reading the section Intro to Firebase of this handbook.

Enable Firestore

Navigate to the Firebase Console, open your project, and click on Firestore. Once on the page, click on the Create database button.

Screen Shot 2021-03-17 at 3.51.01 PM

It will prompt a modal to ask you if you want to start in production mode or test mode. Let's select test mode for now. This is allow you to write, read and delete from your database freely for a period of 30 days. Before releasing your app, remember to go to the Update Firestore permission rules section below to change them. If not, anyone will be able to read, write and delete your database. Click on Next.

Screen Shot 2021-03-17 at 3.54.46 PM

Next, you'll need to choose the location where you want to store your server. Select the one most appropriate to where you are, physically. Remember that you won't be able to change it later. For me, I'll leave it as nam5(us-central). Once chosen, click on Enable.

Screen Shot 2021-03-17 at 3.55.10 PM

Congratulations! Firestore has now been enabled in your project and you can use it in your React project.

Firestore basics

Firestore works with collections and documents. Each document contains key-value pairs. You can nest collections and documents inside one another, but remember that Firestore always alternates between collection-document-collection-document. You can read more about it here.

Write to Firestore

Create a form. This form will allow the user to submit their name, and we'll save the name in Firestore. We'll also use the useInput Hook to get the value of the input field.

import React from "react";
import styled from "styled-components";

import useInput from "./useInput";

const MyForm = () => {
    const name = useInput("");

    return (
        <form>
            <title>Submit your name below</title>
            <input placeholder="Name" {...name} />
            <button type="submit">Submit</button>
        </form>
    );
};

export default MyForm;

Import the getFirebase function we created in the Intro to Firebase section.

import getFirebase from "./firebase"

Create a submitForm function.

const firebase = getFirebase();

const submitForm = async () => {
    event.preventDefault();

    if (firebase) {
      try {
	      const db = firebase.firestore();
	      const docRef = db.collection("names").doc();

        await docRef.set(
          {
            name: name.value
          },
          { merge: true }
        );
        alert("Successfully added to Firestore!");
				name.value = ""
      } catch (error) {
        alert(`An error occured: ${error}`);
        console.log("error", error);
      }
    }
  };

First, we are checking that Firebase is initialized before continuing. Then, we are creating an instance of the database and saving it into the db variable.

Next, we create a reference to the document to which we want to save the name.

Finally, we are setting the name variable in Firestore with the set() function and { merge: true }. It's important to add { merge: true } so that it doesn't overwrite the data you already have in your database.

If everything goes well, we are showing an alert Successfully added to Firestore! and resetting the input field's value to an empty string.

Read from Firestore

You can read from Firestore with the following useEffect hook. It's best to call the data when your component is being mounted, inside of a useEffect.

const [names, setNames] = useState([]);
const firebase = getFirebase();

useEffect(() => {
    const fetchNames = async () => {
      try {
        if (!firebase) return;
        const db = firebase.firestore();
        const ref = db.collection("names");

        const docs = await ref.get();

        let allNames = [];
        docs.forEach((doc) => {
          const data = doc.data();
          allNames.push(data.name);
        });
        setNames(allNames);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchNames();
});

In the above code, we define a new names state and set it to an empty string initially. Next, we are initializing Firebase with the getFirebase function we created in the Intro to Firebase section.

Then, inside of the useEffect, we are creating an async - short for asynchronous - function. We wrap everything in a try...catch statement. If there's no Firebase instance, we are escaping the function immediately.

If there's a Firebase instance, we are creating an instance of the Firestore database, then a reference to the collection we want to read from. We then use the get() function to get the documents. We use the await keyword in front to tell the program to wait for the task to be done before running the next line of code. Then, we iterate over each one.

Finally, we push the name value of each document into the allNames array, and setting it in the local names state with setNames(allNames). We'll be able to use the names state to display each name on the page.

Update Firestore permission rules

Once you're ready to release your app to the public, remember to update your Firestore rules to protect your database and not allow anyone to read and write your database.

Navigate to Cloud Firestore and click on the Rules tab. There, you'll see the rules that are currently applied to your database. If you started in test mode, anyone will be able to read and write to your database for about a month after you created the database.

Screen Shot 2021-03-17 at 4.01.35 PM

You want update the rules depending on how your users will interact with your database. Are they going to only read data? Will they also be able to write data?

In this case, our users are only allowed read the names collection from our database, so we will update the rules like so:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{names=**} {
      allow read: if true;
    }
  }
}

You can read more about Cloud Firestore Rules here.

Cloud Firestore Rules comes with a handy tool called Rules Playground, where you can test your rules before publishing them. Here, my simulated read passed, so I'll click on Publish and we're good to go!

Screen Shot 2021-03-17 at 6.44.54 PM

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Firebase Auth

READ NEXT

Firebase Storage

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Browse all downloads