Reading a List of Documents with the Client SDK
The client SDK uses Reactfire to make it easier to fetch data directly from React components using React Hooks.
Reading a List of Documents with "useFirestoreCollectionData"
In the example below, we will fetch a list of user organizations using the Firebase client SDK and Reactfire.
To do so, we use the React hook useFirestoreCollectionData
, which allows us to stream real-time changes from a collection based on the filters provided.
import {
collection,
where,
query,
CollectionReference,
} from 'firebase/firestore';
import { useFirestore, useFirestoreCollectionData } from 'reactfire';
import { Organization } from '~/lib/organizations/types/organization';
import { ORGANIZATIONS_COLLECTION } from '~/lib/firestore-collections';
export function useFetchUserOrganizations(userId: string) {
const firestore = useFirestore();
const organizationsCollection = collection(
firestore,
ORGANIZATIONS_COLLECTION
) as CollectionReference<WithId<Organization>>;
const userPath = `members.${userId}`;
const operator = '!=';
// we query Firestore for all the organizations
// where the user is a member, therefore where he path
// members.<user_id> is not null
const constraint = where(userPath, operator, null);
const organizationsQuery = query(organizationsCollection, constraint);
return useFirestoreCollectionData(organizationsQuery, {
idField: `id`,
initialData: [],
});
}
Breaking down the code above:
- We first import the
useFirestoreCollectionData
hook fromreactfire
and thecollection
,where
andquery
functions fromfirebase/firestore
. - We then use the
useFirestore
hook to get access to the Firestore instance. - We then create a reference to the
organizations
collection. - We then create a query to fetch all the organizations where the user is a member.
- Finally, we use the
useFirestoreCollectionData
hook to fetch the data from Firestore.
Using the Data
The useFirestoreCollectionData
hook returns an object with the following properties:
data
: the data returned from Firestorestatus
: the status of the request
function UserOrganizations({
userId,
}: React.PropsWithChildren<{
userId: string;
}>) {
const { data, status } = useFetchUserOrganizations(userId);
if (status === 'loading') {
return <p>Loading...</p>;
}
if (status === 'error') {
return <p>Error</p>;
}
return (
<ul>
{data.map((organization) => (
<li key={organization.id}>{organization.name}</li>
))}
</ul>
);
}
Using the Admin SDK
The Admin SDK is used to read data from the server-side.
Reading a List of Documents with "getDocs"
In the example below, we will fetch a list of user organizations using the Firebase Admin SDK.
import getRestFirestore from '~/core/firebase/admin/get-rest-firestore';
export async function getOrganizationsForUser(userId: string) {
const firestore = getRestFirestore();
const organizationsCollection = firestore.collection('organizations');
const result = await organizationsCollection
.where(`members.${userId}`, '!=', null)
.get();
return result.docs.map((doc) => {
return {
...doc.data(),
members: [],
id: doc.id,
role: doc.data().members[userId].role,
};
});
}
You can use the function above in an API route or in a getServerSideProps
function.
To learn more about the above, check out both the Firebase and Reactfire respective documentations.