Firebase
A guestbook stored in Firestore. Signing it, liking a message and deleting one are Firestore writes, and the list is a
Firestore query, all sent as HyperFetch requests through @hyper-fetch/firebase. It runs against your own Firebase
project or the local emulator, and shows a setup screen until one is configured.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";
import { addMessage, deleteMessage, latestMessages, likeMessage, type MessageDoc } from "./api";
import { missingEnv } from "./firebase";
const Setup = () => (
<article>
<header>
<strong>Connect a Firebase project</strong>
</header>
<p>This example reads and writes Firestore, so it needs your own project. These variables are missing:</p>
<ul>
{missingEnv.map((name) => (
<li key={name}>
<code>{name}</code>
</li>
))}
</ul>
<p>
Copy <code>.env.example</code> to <code>.env.local</code>, fill in the web app config from the Firebase console,
and restart <code>npm run dev</code>. To try it without a project, start the Firestore emulator and set only the
project id and <code>VITE_FIREBASE_EMULATOR_HOST</code>.
</p>
</article>
);
const Guestbook = () => {
const [author, setAuthor] = useState("");
const [text, setText] = useState("");
const { data, error, loading, status, refetch } = useFetch(latestMessages);
const { submit, submitting, error: addError, onSubmitSuccess } = useSubmit(addMessage);
onSubmitSuccess(() => {
setText("");
refetch();
});
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
submit({
payload: {
author: author || "anonymous",
text,
likes: 0,
createdAt: Date.now(),
},
});
};
const like = async (message: MessageDoc) => {
const response = await likeMessage
.setParams({ messageId: message.__key })
.send({ payload: { likes: message.likes + 1 } });
if (response.success) refetch();
};
const remove = async (message: MessageDoc) => {
const response = await deleteMessage.setParams({ messageId: message.__key }).send();
if (response.success) refetch();
};
return (
<>
<form onSubmit={handleSubmit}>
<fieldset className="grid">
<input value={author} onChange={(event) => setAuthor(event.target.value)} placeholder="Your name" />
<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Message" required />
<button type="submit" aria-busy={submitting} disabled={submitting}>
Sign
</button>
</fieldset>
{/* Firebase errors, such as permission-denied from security rules, resolve in `error`, never throw. */}
{addError && <small className="error">{addError.message}</small>}
</form>
{loading && !data && <p aria-busy="true">Loading messages...</p>}
{error && <p className="error">Could not load messages: {error.message}</p>}
{status === "emptyResource" && <p className="muted">No messages yet. Be the first to sign.</p>}
<ul className="list">
{data?.map((message) => (
<li key={message.__key}>
<span>
<strong>{message.author}</strong> {message.text}
<br />
<small className="muted">{new Date(message.createdAt).toLocaleString()}</small>
</span>
<span role="group">
<button type="button" className="outline" onClick={() => like(message)}>
Like {message.likes}
</button>
<button type="button" className="outline secondary" onClick={() => remove(message)}>
Delete
</button>
</span>
</li>
))}
</ul>
</>
);
};
export const App = () => (
<main className="container">
<hgroup>
<h1>Firestore guestbook</h1>
<p>Firestore reads and writes as HyperFetch requests, with useFetch, useSubmit and typed responses.</p>
</hgroup>
{missingEnv.length > 0 ? <Setup /> : <Guestbook />}
</main>
);
npx tiged BetterTyped/hyper-fetch/examples/react/firebase hyper-fetch-react-firebase && cd hyper-fetch-react-firebase && npm install && npm run devFirebaseAdapter(getFirestore(app))turns the client into a Firestore client: the endpoint is the Firestore path, the method is the operation.- Query constraints as data:
$orderByand$limitgo inqueryParamsand become a part of the cache key. - Typed documents: responses are typed per request, and the adapter adds the document id as
__key. - Errors in the response: a denied write or a missing index arrives in
error, the request never throws.
Setup
The live preview has no Firebase project, so it shows the setup screen. To run the example:
- Create a project in the Firebase console, add a Firestore database and a web app, and copy its config.
- Copy
.env.exampleto.env.localand fill inVITE_FIREBASE_API_KEY,VITE_FIREBASE_AUTH_DOMAIN,VITE_FIREBASE_PROJECT_IDandVITE_FIREBASE_APP_ID. Restartnpm run dev. - Allow reads and writes to the
messagescollection in your Firestore security rules. While you test, a rule likematch /messages/{id} { allow read, write: if true; }is enough. Lock it down before you ship.
To try it without a project, use the emulator. It needs Java and the Firebase CLI:
npx firebase-tools emulators:start --only firestore --project demo-hyper-fetch
Then set only VITE_FIREBASE_PROJECT_ID=demo-hyper-fetch and VITE_FIREBASE_EMULATOR_HOST=127.0.0.1:8080.
src/firebase.ts calls connectFirestoreEmulator when the host is set.
How it works
-
src/firebase.tsreads theVITE_FIREBASE_*variables, initializes the Firebase app and exportsfirestoreandmissingEnv, the variables that are still empty.Apprenders the setup screen while that list is not empty, so no request is sent without a config. -
src/api.tscreates the client withcreateClient({ url: "" }).setAdapter(FirebaseAdapter(firestore)). Each request names a Firestore path and method:messageswithgetDocsandaddDoc,messages/:messageIdwithupdateDocanddeleteDoc.:messageIdis a regular endpoint param, set withsetParams(). -
latestMessagesis the list request with its constraints already set:export const latestMessages = getMessages.setQueryParams([$orderBy("createdAt", "desc"), $limit(10)]);The constraints are a part of the cache key, so another order or limit is a separate cache entry.
-
Guestbookreads the list withuseFetch(latestMessages)and signs withuseSubmit(addMessage). An empty collection resolves withstatus: "emptyResource"anddata: [], which the component shows as an empty state. -
Like and delete call
likeMessage.setParams({ messageId: message.__key }).send({ payload })anddeleteMessage.setParams(...).send(), thenrefetch()the list. When security rules reject a write,errorholds the Firebase error and the form shows its message.
- Your app already uses Firestore and you want loading state, caching and deduplication without wiring them yourself.
- Firebase and HTTP calls in one codebase that should look and behave the same.
- For live updates, add
@hyper-fetch/socketsand listen withFirebaseSocketsAdapter.
Related
FirebaseAdapter turns Firestore operations into HyperFetch requests. Paths are endpoints, constraints are query params
and errors come back in the response, so Firestore works with the same hooks and cache as any API.
