Firestore in React with typed queries and caching
Each Firestore operation is a request with a Firestore method, so useFetch and useSubmit handle the loading state,
the cache and the types instead of getDocs calls in a useEffect. This page covers every method, what it returns,
and how to query and paginate collections.
- Read documents and collections with
getDocandgetDocs. - Write with
addDoc,setDoc,updateDocanddeleteDoc, with the payload typed per request. - Query collections with typed constraints and page through them with cursors.
Setup
Pass a Firestore instance to FirebaseAdapter. With url: "" every endpoint is the full Firestore path, which
alternates collection and document: teas, teas/sencha, teas/sencha/reviews.
import { createClient } from "@hyper-fetch/core";
import { FirebaseAdapter } from "@hyper-fetch/firebase";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const app = initializeApp({ projectId: "my-project" });
export const client = createClient({ url: "" }).setAdapter(
FirebaseAdapter(getFirestore(app)),
);
export type Tea = {
name: string;
type: "Green" | "Black" | "Oolong";
year: number;
};
// __key is the document id, added by the adapter
export type TeaDoc = Tea & { __key: string };
Methods
| Method | Path | data | extra |
|---|---|---|---|
getDocs | collection | documents with __key, [] when empty | ref (CollectionReference), snapshot |
getDoc | document | the document with __key, or null | ref (DocumentReference), snapshot |
addDoc | collection | the payload plus the new __key | ref of the new document |
setDoc | document | the payload | ref |
updateDoc | document | the payload | ref |
deleteDoc | document | null | ref |
getDoc is the default, so a request without method reads one document. An empty result resolves with
status: "emptyResource".
Read
export const getTeas = client.createRequest<{ response: TeaDoc[] }>()({
endpoint: "teas",
method: "getDocs",
});
export const getTea = client.createRequest<{ response: TeaDoc | null }>()({
endpoint: "teas/:teaId",
});
const { data } = await getTea.setParams({ teaId: "sencha" }).send();
// { __key: "sencha", name: "Sencha", ... }, or null with status "emptyResource"
Write
addDoc creates a document with a generated id. setDoc creates or replaces a document at a known id, and merges into
it with options: { merge: true }. updateDoc changes the given fields and fails with Firestore's not-found error
when the document does not exist.
export const addTea = client.createRequest<{
response: TeaDoc;
payload: Tea;
}>()({
endpoint: "teas",
method: "addDoc",
});
export const mergeTea = client.createRequest<{
response: Partial<Tea>;
payload: Partial<Tea>;
}>()({
endpoint: "teas/:teaId",
method: "setDoc",
options: { merge: true },
});
export const deleteTea = client.createRequest<{ response: null }>()({
endpoint: "teas/:teaId",
method: "deleteDoc",
});
// data.__key is the new id
const { data } = await addTea.send({
payload: { name: "Sencha", type: "Green", year: 2024 },
});
await mergeTea.setParams({ teaId: "sencha" }).send({ payload: { year: 2025 } });
Querying
Pass queryParams a callback that builds the constraints. With the document type on the request, fields and values are
checked.
import type { FirestoreQueryParams } from "@hyper-fetch/firebase";
export const listTeas = client.createRequest<{
response: TeaDoc[];
queryParams?: FirestoreQueryParams<Tea>;
}>()({
endpoint: "teas",
method: "getDocs",
});
const { data } = await listTeas.send({
queryParams: (c) =>
c
.where("type", "==", "Green")
.where("year", ">=", 2020)
.orderBy("year", "desc")
.limit(20),
});
| Chain method | Typed by the document |
|---|---|
where(field, op, value) | field exists, value matches it (an array for "in") |
orderBy(field, direction?) | field exists |
limit(n) | - |
startAt, startAfter, endAt, endBefore | one value per orderBy, in order |
Nested fields use dots ("origin.country"). __key is the document id, not a field, so you cannot filter on it. A
range filter combined with orderBy on another field needs a composite index, and Firestore reports a missing one in
response.error with a link that creates it.
Pagination
Cursors take one value per orderBy, in the same order. To load the next page, start after the last document you have.
Each page has its own cache entry.
const page1 = await listTeas.send({
queryParams: (c) => c.orderBy("year", "desc").orderBy("name").limit(20),
});
const last = page1.data?.at(-1);
const page2 = await listTeas.send({
queryParams: (c) =>
c
.orderBy("year", "desc")
.orderBy("name")
.startAfter(last!.year, last!.name)
.limit(20),
});
Constraints as data
queryParams also takes the array the callback resolves to, built with $where, $orderBy, $limit and the
$-cursors. Use it to build a query step by step.
import { $orderBy, $where } from "@hyper-fetch/firebase";
import type { FirestoreConstraint } from "@hyper-fetch/firebase";
const constraints: FirestoreConstraint[] = [];
if (onlyGreen) constraints.push($where("type", "==", "Green"));
constraints.push($orderBy("year", "desc"));
const greenTeas = listTeas.setQueryParams(constraints);
Firestore in your app
In React, useFetch reads and useSubmit writes. Each filter combination is cached and deduplicated on its own.
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { addTea, listTeas } from "./api/teas";
export const TeaList = () => {
const { data, loading } = useFetch(
listTeas.setQueryParams((c) => c.where("type", "==", "Green")),
);
const { submit, submitting } = useSubmit(addTea);
if (loading) return <p>Loading...</p>;
return (
<div>
{data?.map((tea) => (
<p key={tea.__key}>{tea.name}</p>
))}
<button
disabled={submitting}
onClick={() =>
submit({ payload: { name: "Sencha", type: "Green", year: 2024 } })
}
>
Add tea
</button>
</div>
);
};
For updates as they happen, use a listener instead, see realtime listening.
Web and admin differences
Firestore requests work the same in @hyper-fetch/firebase-admin,
except:
| Topic | @hyper-fetch/firebase (web) | @hyper-fetch/firebase-admin (server) |
|---|---|---|
setDoc data | the payload | the Admin SDK WriteResult |
| Security rules | enforced for the signed-in user | bypassed |
getDocsandgetDocread;addDoc,setDoc,updateDocanddeleteDocwrite.- Documents and list items come with
__key, their document id. setDocreplaces unless the request hasoptions: { merge: true }.- Queries are a
queryParamscallback checked against the document; cursors take one value perorderBy.
Next steps
Runnable example: Firebase, a Firestore guestbook with typed reads, writes and constraints.