Core Concepts
Subscriptions

Subscriptions

Use the subscribe method of Reflect to watch for changes to data in the room:

r.subscribe(
  (tx) => tx.get("counter"),
  (value) => {
    myElm.textContent = value;
  },
);

Queries

The function that is passed to subscribe is called a query. Queries can do multiple reads from Reflect and return any JSON-compatible value.

For example to subscribe to all incomplete todos:

r.subscribe(
  async (tx) => {
    const todos = await tx.scan({ prefix: `/todo/` }).toArray();
    return todos.filter((t) => !t.complete);
  },
  (todos) => {
    // render todos
  },
);

Subscriptions are fast. Queries are only re-run when data they depend on changes. And the subscription doesn't fire its callback unless the value returned from the query changes, reducing re-renders.

React

In React you can use the useSubscribe hook:

import { useSubscribe } from "@rocicorp/reflect/react";
 
const numTodos = useSubscribe(r, async (tx) => {
  const todos = await tx.scan({ prefix: "/todo/" }).keys().toArray();
  return todos.length;
});