Skip to main content
Version: v10.5.0

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.

Purpose
  1. Read documents and collections with getDoc and getDocs.
  2. Write with addDoc, setDoc, updateDoc and deleteDoc, with the payload typed per request.
  3. 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.

api/firebase.ts
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​

MethodPathdataextra
getDocscollectiondocuments with __key, [] when emptyref (CollectionReference), snapshot
getDocdocumentthe document with __key, or nullref (DocumentReference), snapshot
addDoccollectionthe payload plus the new __keyref of the new document
setDocdocumentthe payloadref
updateDocdocumentthe payloadref
deleteDocdocumentnullref

getDoc is the default, so a request without method reads one document. An empty result resolves with status: "emptyResource".

Read​

api/teas.ts
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.

api/teas.ts
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.

api/teas.ts
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 methodTyped 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, endBeforeone 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.

api/teas.ts
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.

api/teas.ts
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.

TeaList.tsx
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 datathe payloadthe Admin SDK WriteResult
Security rulesenforced for the signed-in userbypassed

Summary
  • getDocs and getDoc read; addDoc, setDoc, updateDoc and deleteDoc write.
  • Documents and list items come with __key, their document id.
  • setDoc replaces unless the request has options: { merge: true }.
  • Queries are a queryParams callback checked against the document; cursors take one value per orderBy.

Next steps​

Runnable example: Firebase, a Firestore guestbook with typed reads, writes and constraints.

Realtime listening
Keep Firestore queries live with onSnapshot listeners.
DB with Firestore
Firestore collections that several views read and keep live.
FirestoreQueryParams API reference
The query params type that checks fields and values.