Skip to main content
Version: v10.5.0

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.

Purpose
  1. Listen to Firestore documents and queries, or Realtime Database paths, with typed data.
  2. Filter live queries with setQueryParams((c) => ...), the same chain as requests.
  3. 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.

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

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

FieldFirestoreRealtime Database
datadocument with __key, or list of documentsvalue, or list as described for get
extra.status"success" or "emptyResource""success" or "emptyResource"
extra.refDocumentReference or QueryDatabaseReference
extra.snapshotDocumentSnapshot or QuerySnapshotDataSnapshot
extra.groupedResultwith groupByChangeType, see below-

Filtering​

Listeners take query params like requests: a callback that builds the constraints, or the $-helper array.

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

OptionDatabaseEffect
groupByChangeTypeFirestoreOn collection listeners, adds extra.groupedResult with the added, modified and removed documents
onlyOnceRealtime DatabaseReceives 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.

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

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

GreenTeas.tsx
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 adapterFirebaseSocketsAdapterFirebaseSocketsAdminAdapter
Firestore socket connect(), disconnect()toggle the network of the instancethrow, stop listeners with their stop function
Realtime document listener datathe valuethe value plus __key
Firestore listener extraref, snapshot, status, groupedResultthe same, plus unsubscribe
Documents in groupedResultwith __keywithout __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 teas with different constraints would mix results. Give them different sockets.
  • socket.disconnect() takes the whole Firebase instance offline: disableNetwork for Firestore, goOffline for 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.

Summary
  • 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 with groupByChangeType, read once with onlyOnce.
  • Keep one listener per topic on a socket, and stop listeners with the function listen returns.

Next steps​

useListener
Listen to a socket topic in a React component.
DB with Firestore
Live Firestore collections that several views share.
FirebaseSocketsAdapter API reference
The socket adapter factory and its listener types.