Firebase Realtime Database in React
Each Realtime Database operation is a request with a Realtime Database method, so useFetch and useSubmit handle
loading, caching and types instead of snapshots converted by hand. This page covers reading and writing, how lists are
returned, and how to query them.
- Read values and lists with
get. - Write with
set,push,updateandremove, with the payload typed per request. - Query lists with ordering, limits and cursors.
Setup
Pass a Realtime Database instance to FirebaseAdapter. With url: "" every endpoint is the full database path.
import { createClient } from "@hyper-fetch/core";
import { FirebaseAdapter } from "@hyper-fetch/firebase";
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const app = initializeApp({
projectId: "my-project",
databaseURL: "https://my-project.firebaseio.com",
});
export const client = createClient({ url: "" }).setAdapter(
FirebaseAdapter(getDatabase(app)),
);
export type Message = { text: string; author: string; sentAt: number };
The Realtime Database is one JSON tree addressed by path, and its queries order by one child, key or value. Pick Firestore for documents in collections with several filters.
Methods
| Method | data | extra |
|---|---|---|
get | the value, or a list, see below | ref (DatabaseReference), snapshot |
set | the payload | ref |
push | the payload plus the new __key | ref of the new child, key |
update | the payload | ref |
remove | null | ref |
get is the default, so a request without method reads.
Read
export const getMessages = client.createRequest<{
response: (Message & { __key: string })[] | null;
}>()({
endpoint: "rooms/:roomId/messages",
});
const { data } = await getMessages.setParams({ roomId: "general" }).send();
Write
set replaces the value at the path, and a null payload deletes it. push adds a child with a generated key.
update writes only the given children and keeps the others.
export const sendMessage = client.createRequest<{
response: Message & { __key: string };
payload: Message;
}>()({
endpoint: "rooms/:roomId/messages",
method: "push",
});
export const editMessage = client.createRequest<{
response: Partial<Message>;
payload: Partial<Message>;
}>()({
endpoint: "rooms/:roomId/messages/:messageId",
method: "update",
});
const { data } = await sendMessage
.setParams({ roomId: "general" })
// data.__key is the generated key
.send({ payload: { text: "Hi", author: "ann", sentAt: Date.now() } });
await editMessage
.setParams({ roomId: "general", messageId: data!.__key })
.send({ payload: { text: "Hi all" } });
Values and lists
get decides how to return data from the number of path segments, the same rule as Firestore documents and collections.
| Path | Segments | data |
|---|---|---|
rooms, rooms/a/messages | odd | an array of children, each spread into an object with its __key |
rooms/a, topics/general | even | the stored value as is |
A list keeps the order of the query. An empty list is null with status: "emptyResource". Each child is spread into
an object, so a list of plain strings returns entries like { 0: "c", __key: "2" }: store objects, or read such data
from an even-segment path.
Querying
Pass queryParams a callback that builds the constraints. Type the request with the type of the list's children, and
paths and values are checked.
import type { RealtimeDBQueryParams } from "@hyper-fetch/firebase";
export const listMessages = client.createRequest<{
response: (Message & { __key: string })[] | null;
queryParams?: RealtimeDBQueryParams<Message>;
}>()({
endpoint: "rooms/:roomId/messages",
method: "get",
});
const { data } = await listMessages.setParams({ roomId: "general" }).send({
queryParams: (c) => c.orderByChild("sentAt").limitToLast(50),
});
| Chain method | Notes |
|---|---|
orderByChild(path) | nested children use /: "author/name" |
orderByKey(), orderByValue() | one orderBy* per query, enforced by the types |
limitToFirst(n), limitToLast(n) | - |
equalTo(value, key?) | after an orderBy*, value has the child's type |
startAt, startAfter, endAt, endBefore | after an orderBy*, with (value, key?) |
orderByChild needs an .indexOn rule for that child. Without it the request resolves with status: "error" and the
message Index not defined, add ".indexOn" ....
Pagination
The optional key of a cursor breaks ties between children with the same value, so pages stay stable when values
repeat.
const page1 = await listMessages.setParams({ roomId: "general" }).send({
queryParams: (c) => c.orderByChild("sentAt").limitToFirst(50),
});
const last = page1.data?.at(-1);
const page2 = await listMessages.setParams({ roomId: "general" }).send({
queryParams: (c) =>
c
.orderByChild("sentAt")
.startAfter(last!.sentAt, last!.__key)
.limitToFirst(50),
});
Constraints as data
queryParams also takes the array the callback resolves to, built with $orderByChild, $limitToLast, $equalTo and
the other $-helpers.
Realtime Database in your app
In React, useFetch reads once per query and caches the result.
import { useFetch } from "@hyper-fetch/react";
import { listMessages } from "./api/messages";
export const LastMessages = ({ roomId }: { roomId: string }) => {
const { data } = useFetch(
listMessages
.setParams({ roomId })
.setQueryParams((c) => c.orderByChild("sentAt").limitToLast(50)),
);
return data?.map((message) => <p key={message.__key}>{message.text}</p>);
};
To show new messages as they arrive, use a listener, see realtime listening.
Web and admin differences
Realtime Database requests work the same in
@hyper-fetch/firebase-admin, except:
| Topic | @hyper-fetch/firebase (web) | @hyper-fetch/firebase-admin (server) |
|---|---|---|
| Database instance | getDatabase(app) from firebase/database | getDatabase() from firebase-admin/database, with databaseURL in initializeApp |
| Security rules | enforced for the signed-in user | bypassed |
getreads;set,push,updateandremovewrite.- Odd-segment paths return lists of objects with
__key; even-segment paths return the value as is. - Queries are a
queryParamscallback with oneorderBy*; cursors take a value and an optional tie key. - Missing
.indexOnrules and other Firebase errors arrive inresponse.error.