Firestore realtime updates in React
FirebaseSocketsAdapter runs Firestore onSnapshot and Realtime Database onValue through a
Socket. Each path becomes a typed Listener that receives the full
current result on every change, and useListener starts and stops it with the component.
- Listen to Firestore documents and queries, or Realtime Database paths, with typed data.
- Filter live queries with
setQueryParams((c) => ...), the same chain as requests. - Group Firestore changes into added, modified and removed, or read a Realtime Database path once.
Setup
Install @hyper-fetch/sockets, then create a socket per database. Call FirebaseSocketsAdapter(db) inside each
new Socket(...): an adapter binds to the socket it was created for, so one adapter shared by two sockets sends every
listener to the last socket's url.
import { Socket } from "@hyper-fetch/sockets";
import { FirebaseSocketsAdapter } from "@hyper-fetch/firebase";
import { getDatabase } from "firebase/database";
import { getFirestore } from "firebase/firestore";
import { app } from "./firebase";
export const firestoreSocket = new Socket({
url: "",
adapter: FirebaseSocketsAdapter(getFirestore(app)),
});
export const realtimeSocket = new Socket({
url: "",
adapter: FirebaseSocketsAdapter(getDatabase(app)),
});
Listening
The listener path is socket.url + topic, and topic params work like endpoint params. listen returns a function that
stops the Firebase subscription.
type TeaDoc = {
__key: string;
name: string;
type: "Green" | "Black";
year: number;
};
export const onTeas = firestoreSocket.createListener<TeaDoc[]>()({
topic: "teas",
});
export const onTea = firestoreSocket.createListener<TeaDoc | null>()({
topic: "teas/:teaId",
});
const stop = onTea
.setParams({ teaId: "sencha" })
.listen(({ data }) => render(data));
stop();
Every snapshot is delivered once, as the full current document or list. Replace your state with it, do not append.
| Field | Firestore | Realtime Database |
|---|---|---|
data | document with __key, or list of documents | value, or list as described for get |
extra.status | "success" or "emptyResource" | "success" or "emptyResource" |
extra.ref | DocumentReference or Query | DatabaseReference |
extra.snapshot | DocumentSnapshot or QuerySnapshot | DataSnapshot |
extra.groupedResult | with groupByChangeType, see below | - |
Filtering
Listeners take query params like requests: a callback that builds the constraints, or the $-helper array.
export const onGreenTeas =
firestoreSocket
.createListener<TeaDoc[]>()({
topic: "teas",
})
.setQueryParams((c) =>
c
.where("type", "==", "Green")
.orderBy("year", "desc")
.limit(20),
);
export const onLastMessages =
realtimeSocket
.createListener<Message[]>()({
topic: "rooms/general/messages",
})
.setQueryParams((c) =>
c
.orderByChild("sentAt")
.limitToLast(50),
);
Field names are not checked on listeners, because a listener's query params are not tied to a document type. The
options.constraints of earlier versions still works and is deprecated.
Options
| Option | Database | Effect |
|---|---|---|
groupByChangeType | Firestore | On collection listeners, adds extra.groupedResult with the added, modified and removed documents |
onlyOnce | Realtime Database | Receives the first value and stops |
Grouping changes
groupedResult is null on document listeners and when a snapshot has no document changes. Its documents carry
__key, like data.
const onTeasChanges =
firestoreSocket.createListener<
TeaDoc[]
>()({
topic: "teas",
options: {
groupByChangeType: true,
},
});
onTeasChanges.listen(
({ data, extra }) => {
render(data);
if (extra.groupedResult)
notify(
`${extra.groupedResult.added.length} new teas`,
);
},
);
Reading once
const onConfig =
realtimeSocket.createListener<Config | null>()(
{
topic: "config",
options: { onlyOnce: true },
},
);
Listeners in your app
In React, useListener starts the listener on mount and stops it on unmount.
import { useListener } from "@hyper-fetch/react";
import { onGreenTeas } from "./api/live";
export const GreenTeas = () => {
const { data } = useListener(onGreenTeas);
return data?.map((tea) => <p key={tea.__key}>{tea.name}</p>);
};
Web and admin differences
Listeners work the same in
@hyper-fetch/firebase-admin, except:
| Topic | @hyper-fetch/firebase (web) | @hyper-fetch/firebase-admin (server) |
|---|---|---|
| Socket adapter | FirebaseSocketsAdapter | FirebaseSocketsAdminAdapter |
Firestore socket connect(), disconnect() | toggle the network of the instance | throw, stop listeners with their stop function |
Realtime document listener data | the value | the value plus __key |
Firestore listener extra | ref, snapshot, status, groupedResult | the same, plus unsubscribe |
Documents in groupedResult | with __key | without __key |
Limits
- One listener per topic on a socket. Listeners on the same socket and topic receive each other's snapshots, so two
listeners on
teaswith different constraints would mix results. Give them different sockets. socket.disconnect()takes the whole Firebase instance offline:disableNetworkfor Firestore,goOfflinefor the Realtime Database. Your requests go offline too. To stop one listener, call its stop function.- Sockets cannot emit. Firebase sockets only receive. Write with requests.
- Create each socket with its own
FirebaseSocketsAdapter(db). - The listener path is
socket.url + topic, and every snapshot arrives as the full current result. - Filter with
setQueryParams((c) => ...), group withgroupByChangeType, read once withonlyOnce. - Keep one listener per topic on a socket, and stop listeners with the function
listenreturns.