Basic Usage

The simplest usage of useDocument is to provide a DocumentReference to the hook. This will fetch the document and return its data. The hook will also automatically update the component with the latest data whenever the document changes.

Dynamic Paths

It’s very common in Firebase applications to include the user’s ID in the path to 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.

To connect to a document at a dynamic path, we can provide a function instead of a DocumentReference. The function should return a DocumentReference and its first argument will be the user ID of the active user.

For example, here’s how we can fetch the active user’s own profile:

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 User and their current Company on the same page. In this case, the company document we want to connect to depends on the user document. This is a great use case for useDocument:

In this example, Firebridge will first create the user reference and fetch the user document. Once the user document is fetched, and their companyId is defined, Firebridge will create the company reference and fetch the company document.

Whether the user changes, or the company changes, or the user switches companies, Firebridge will automatically update the component with the latest data.