Skip to main content
Version: v10.5.0

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.

Purpose
  1. Read values and lists with get.
  2. Write with set, push, update and remove, with the payload typed per request.
  3. Query lists with ordering, limits and cursors.

Setup​

Pass a Realtime Database instance to FirebaseAdapter. With url: "" every endpoint is the full database path.

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

Methoddataextra
getthe value, or a list, see belowref (DatabaseReference), snapshot
setthe payloadref
pushthe payload plus the new __keyref of the new child, key
updatethe payloadref
removenullref

get is the default, so a request without method reads.

Read​

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

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

PathSegmentsdata
rooms, rooms/a/messagesoddan array of children, each spread into an object with its __key
rooms/a, topics/generaleventhe 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.

api/messages.ts
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 methodNotes
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, endBeforeafter 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.

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

LastMessages.tsx
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 instancegetDatabase(app) from firebase/databasegetDatabase() from firebase-admin/database, with databaseURL in initializeApp
Security rulesenforced for the signed-in userbypassed

Summary
  • get reads; set, push, update and remove write.
  • Odd-segment paths return lists of objects with __key; even-segment paths return the value as is.
  • Queries are a queryParams callback with one orderBy*; cursors take a value and an optional tie key.
  • Missing .indexOn rules and other Firebase errors arrive in response.error.

Next steps​

Realtime listening
Keep Realtime Database paths live with onValue listeners.
RealtimeDBQueryParams API reference
The query params type that checks children and values.