TypeScript logo but with a P
Patrick Spafford Software Engineer

React Firestore Listener

Oct 27, 2021

views


The NPM package, react-firestore-listener, is a React hook written in TypeScript that makes it easy to subscribe to document collections in Firebase. Under the hood, it uses the Firebase SDK to query your Firestore documents.

Here we have an example of how you could use this package in your own project. We query our Firestore database for a list of frogs (and toads). When you reorder them, the useFirestoreListener hook makes sure that the UI updates with the proper order, without you having to do anything else.

Note: The reordering and styles are omitted from the example code for simplicity.


import React from "react"
import useFirestoreListener from "react-firestore-listener"
import { getApp, initializeApp } from "firebase/app"

const config = {
  // insert your Firebase config here
}

/*
We need to make sure that Firebase is initialized before we can listen to documents.
*/
if (!getApp()) {
  initializeApp(config)
}

interface Frog {
  name: string
}

const App = () => {
  const frogs = useFirestoreListener<Frog>({ collection: "frogs" })
  return (
    <div>
      <div>Reorder The Frogs</div>
      <ul>
        {frogs.map((frog) => {
          return (
            <li key={frog.name}>
              <img src={frog.image} />
              <span>{frog.name}</span>
            </li>
          )
        })}
      </ul>
    </div>
  )
}
Reorder The Frogs
Loading...