useCollection
The useCollection
hook makes it simple to connect with realtime Firestore collections, even when paths are dynamic or depend on the ID of the current user. This hook is particularly useful in React applications where collection paths depend on runtime values like user IDs or route parameters.
Basic Usage
The simplest usage of useCollection
is to provide a CollectionReference
or QueryReference
to the hook. This will fetch the documents and return their data. The hook will also automatically update the component with the latest data whenever a document changes.
First, let’s connect to all of the books in our Firestore database:
Dynamic Paths
It’s very common in Firebase applications to include the user’s ID inside a document. This makes it simple to write Firestore security rules that restrict access to documents based on the user’s ID. However, this also means that we need to know the user’s ID before we can fetch the document.
Instead of providing a function instead of a CollectionReference
or QueryReference
directly, we’ll need to provide a function which can produce one. This function’s first argument will be the user ID of the active user.
Custom Route Parameters
We can also include other string parameters in the document path, and ensure they exist before fetching the document. This is a common pattern in Firebase applications on React where document paths might depend on other dynamic values (e.g., route parameters). Firebridge makes it easy to manage these dependencies with a similar syntax to the useEffect
hook.
For example, we might want to display a set of Book
documents that share the same authorId
as a the book we’re currently displaying. In this case, the query we want to connect to depends on the book document.