Firestore
Add to favorites
Enable Firestore as your database in your React application

Advanced React Hooks Handbook
1
Intro to Firebase
6:59
2
Firebase Auth
11:59
3
Firestore
10:51
4
Firebase Storage
6:40
5
Serverless Email Sending
10:02
6
Geocoding with Mapbox
9:24
7
Contentful Part 1
4:59
8
Contentful Part 2
8:52
9
Gatsby and Shopify Part 1
5:20
10
Gatsby and Shopify Part 2
13:21
11
Gatsby and Shopify Part 3
14:32
12
Creating Stripe Account and Product
5:18
13
Adding Stripe.js to React
5:54
14
Stripe Checkout Client Only
18:18
15
PayPal Checkout
31:21
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.
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.
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.
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.
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!
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.
Templates and source code
Download source files
Download the videos and assets to refer and learn offline without interuption.
Design template
Source code for all sections
Video files, ePub and subtitles
Browse all downloads
1
Intro to Firebase
Learn about Firebase and set it up in your React project
6:59
2
Firebase Auth
Set up authentication in your React application using Firebase Auth
11:59
3
Firestore
Enable Firestore as your database in your React application
10:51
4
Firebase Storage
Enable Firebase Storage in your application to store photos or videos from users
6:40
5
Serverless Email Sending
Use EmailJS to send an email without backend
10:02
6
Geocoding with Mapbox
Create an address autocomplete with Mapbox's Geocoding API
9:24
7
Contentful Part 1
Create a Contentful account, add a model and content
4:59
8
Contentful Part 2
How to use the Content Delivery API to fetch data from Contentful
8:52
9
Gatsby and Shopify Part 1
Create a Shopify store, generate a password and add products to the store
5:20
10
Gatsby and Shopify Part 2
Connect Shopify to Gatsby and display all products
13:21
11
Gatsby and Shopify Part 3
Create a seamless checkout experience with Shopify and Gatsby
14:32
12
Creating Stripe Account and Product
Start integrating with Stripe and set up an account, product and price
5:18
13
Adding Stripe.js to React
Loading Stripe.js library to your React client application
5:54
14
Stripe Checkout Client Only
Accept payment with Stripe Checkout without backend
18:18
15
PayPal Checkout
Integrate online payment with PayPal
31:21
Meet the instructor
We all try to be consistent with our way of teaching step-by-step, providing source files and prioritizing design in our courses.
Stephanie Diep
iOS and Web developer
Developing web and mobile applications while learning new techniques everyday
7 courses - 36 hours

Build Quick Apps with SwiftUI
Apply your Swift and SwiftUI knowledge by building real, quick and various applications from scratch
11 hrs

Advanced React Hooks Handbook
An extensive series of tutorials covering advanced topics related to React hooks, with a main focus on backend and logic to take your React skills to the next level
3 hrs

SwiftUI Concurrency
Concurrency, swipe actions, search feature, AttributedStrings and accessibility were concepts discussed at WWDC21. This course explores all these topics, in addition to data hosting in Contentful and data fetching using Apollo GraphQL
3 hrs

SwiftUI Combine and Data
Learn about Combine, the MVVM architecture, data, notifications and performance hands-on by creating a beautiful SwiftUI application
3 hrs

SwiftUI Advanced Handbook
An extensive series of tutorials covering advanced topics related to SwiftUI, with a main focus on backend and logic to take your SwiftUI skills to the next level
4 hrs

React Hooks Handbook
An exhaustive catalog of React tutorials covering hooks, styling and some more advanced topics
5 hrs

SwiftUI Handbook
A comprehensive series of tutorials covering Xcode, SwiftUI and all the layout and development techniques
7 hrs