useLive
Hook that listens to one of your app’s realtime channels and calls your function whenever the server sends a broadcast.
Usage
app/orders/page.tsx
import { useApiClient } from "app/api";
import { useLive, useRequest } from "app/hooks";
export default function OrdersBoard() {
const api = useApiClient();
const { data, refresh } = useRequest(() => api.orders.list({ status: "new" }));
useLive("orders", () => refresh()); // reload when anyone changes an order
// …
}app/orders/repository.ts
import { broadcast } from "manh/realtime";
// after the write
broadcast("orders", { id: order.id });Signature
app/hooks.ts
function useLive<T = unknown>(
channel: string | string[],
onMessage: (data: T, channel: string) => void,
opts?: { user?: boolean },
): { connected: boolean };Parameters
channel: a channel name or an array of names. Names use lowercase letters, digits and: _ -, up to 64 characters.onMessage(data, channel): runs with the databroadcastsent and the channel it arrived on.opts.user:truealso joins the private channeluser:<your id>. Requires a signed-in user: the hook sends the token from signIn to prove the id.
Returns
{ connected }: true while connected to the server. When the connection drops, the hook reconnects by itself, waiting longer each time up to 30 seconds between tries.
Examples
Notify exactly one person when a task is assigned to them:
app/layout.tsx
const { notification } = App.useApp();
useLive("tasks", (m: any, channel) => {
if (channel.startsWith("user:")) notification.info({ message: `Task #${m.id} was assigned to you` });
}, { user: true });app/tasks/repository.ts
broadcast(`user:${task.assigneeId}`, { type: "assigned", id: task.id });- Any channel other than
user:<id>can be heard by anyone who opens the app. Send ids or a “changed” signal, then reload the data through the API (which checks permissions). - Keep messages small. Load details with useApiClient.
- Each plan caps the number of simultaneous realtime connections per app (Free 100).
Next steps
- broadcast: the server side.
- useRequest:
refreshto reload on a message.
Last updated