Skip to main content

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.

intermediatefirebaseuseFetchuseSubmitparams
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>
);
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/firebase hyper-fetch-react-firebase && cd hyper-fetch-react-firebase && npm install && npm run dev
What it shows
  1. FirebaseAdapter(getFirestore(app)) turns the client into a Firestore client: the endpoint is the Firestore path, the method is the operation.
  2. Query constraints as data: $orderBy and $limit go in queryParams and become a part of the cache key.
  3. Typed documents: responses are typed per request, and the adapter adds the document id as __key.
  4. 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:

  1. Create a project in the Firebase console, add a Firestore database and a web app, and copy its config.
  2. Copy .env.example to .env.local and fill in VITE_FIREBASE_API_KEY, VITE_FIREBASE_AUTH_DOMAIN, VITE_FIREBASE_PROJECT_ID and VITE_FIREBASE_APP_ID. Restart npm run dev.
  3. Allow reads and writes to the messages collection in your Firestore security rules. While you test, a rule like match /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​

  1. src/firebase.ts reads the VITE_FIREBASE_* variables, initializes the Firebase app and exports firestore and missingEnv, the variables that are still empty. App renders the setup screen while that list is not empty, so no request is sent without a config.

  2. src/api.ts creates the client with createClient({ url: "" }).setAdapter(FirebaseAdapter(firestore)). Each request names a Firestore path and method: messages with getDocs and addDoc, messages/:messageId with updateDoc and deleteDoc. :messageId is a regular endpoint param, set with setParams().

  3. latestMessages is 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.

  4. Guestbook reads the list with useFetch(latestMessages) and signs with useSubmit(addMessage). An empty collection resolves with status: "emptyResource" and data: [], which the component shows as an empty state.

  5. Like and delete call likeMessage.setParams({ messageId: message.__key }).send({ payload }) and deleteMessage.setParams(...).send(), then refetch() the list. When security rules reject a write, error holds the Firebase error and the form shows its message.

When to use it
  • 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/sockets and listen with FirebaseSocketsAdapter.

Summary

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.