DEV Community

Cover image for Firebase Miniseries 2: Firestore Part 1
Uriel Bitton
Uriel Bitton

Posted on

Firebase Miniseries 2: Firestore Part 1

Intro

Firebase's firestore API is a powerful API managed database that lets us store data like a regular database but with the simplicity and easy of API GET and POST requests.

Gettting data from firestore can be done so easil, it only requires a couple lines to get data and a couple lines to set data. This is what makes firebase such a favorite amongst web developers. Its simplicity is unmatched and the DX (Developer Experience) is incredible.

In this 2 part post, i will teach you the best practice methods and tricks to work with firebase's firestore database and make it so easy to learn, you'll be using firebase in every project from now on.

Firestore Setup

After setting up our firebase app, we can go into the sidebar > firestore database and click the button enable on the header. If you haven't read my previous post on auth, i explain there how to setup a firebase app. A popup will open prompting you to setup your firestore database. Choose production mode. On the next slide choose the location of your firestore closest to where your app will be used for the majority of your users. Once the setup is complete, you will be redirected to the firestore database page.

Next, we setup the config firebase file in order to access the firestore API:

import firebase from "firebase"

const config = {
  apiKey: "fill in with your real values",
  authDomain: "fill in with your real values",
  projectId: "fill in with your real values",
  storageBucket: "fill in with your real values",
  messagingSenderId: "fill in with your real values",
  appId: "fill in with your real values"
}
const firebaseApp = firebase.initializeApp(config)

const db = firebaseApp.firestore()
const auth = firebaseApp.auth()
const storage = firebaseApp.storage()

export { db, auth, storage } 
Enter fullscreen mode Exit fullscreen mode

Let's save that to a file called firebase.js inside a folder called firebase which is in our src folder (root folder in next js).

The first step will be about writing data, the second step will be about reading the data.

Writing

Usually when your app creates a user from the register file, you want to write that new user's information to a collection called users. In short, firebase's auth user object is read, delete and update only, you cannot write new properties to it, so to store custom data like address, city, country, etc, we need to create a new 'user' object inside a new collection called users, with the same user uid as the auth user's uid. That way we can get the currently logged in user's custom data by "finding the user inside the users collection with userID == to the auth user's uid. If it seems complicated it wil become clear soon.

After successful account creation let's run this function to create a new user inside a users collection.

import { db } from 'path/to/firebase/config' //import db for firestore api calls
auth.createUserWithEmailAndPassword() //use code from my previous auth post 
.then(user => { //this user object contains the auth user data
  //let's create a new user doc inside a collection and call it users
  db.collection('users')
  .doc(user.uid)
  .set({
    firstName: 'Walter',
    lastName: 'White',
    city: 'Albuquerque',
    state: 'New Mexico,
    country: 'U.S.',
    photoURL: ''
  })
})
Enter fullscreen mode Exit fullscreen mode

This will then create our user doc inside our users collection.

We're now ready to make get calls to our firestore. In other words, display the information we have on our users. In our project let's create a file called MyProfile.js (I will be using React again for this code, but again most code logic can be implemented the same using Vanilla JS).

Let's start writing a basic component template:

import React from 'react'

export default function ProfilePage() {

  useEffect(() => {

  },[])

  return (
   //render whatever UI you want here, user info, name, image, etc.
  )
}
Enter fullscreen mode Exit fullscreen mode

Now to get/fetch data from firestore we'll make a call to the firestore api by importing the 'db' function we created in our config file, inside the useEffect like so:

import { db } from 'path/to/firebase/config'

const [profileUser, setProfileUser] = useState(null)
const userID = '' //get user's uid from url parameters

useEffect(() => {
  db
  .collection('users')
  .doc(userID)
  .get()
  .then(snap => {
    setProfileUser(snap.data()) //get function returns a snapshot of user's doc in firestore
  })
},[])
Enter fullscreen mode Exit fullscreen mode

Now we can use profileUser in our UI like so:

<h4>First Name: {profileUser?.firstName}</h4>
<h4>Last Name: {profileUser?.lastName}</h4>
<h4>City: {profileUser?.city}</h4>
<h4>State: {profileUser?.state}</h4>
Enter fullscreen mode Exit fullscreen mode

Voila, you've just written and read data to and from firebase's firestore database. All in only a few lines of code.

Conclusion

The simplicity of firebase's firestore API is what makes it popular and fun to use as a database. With firestore's API we can easily make post and get calls by simply calling the 'db' function and use .set() or .get() to get or set data to/from our database.

Hope you enjoyed this one, and see you in Part 2, where i go into advanced firestore concepts.

Top comments (0)