Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Subscribe to a query

Keep a query's result up to date in an app, as the luna's data changes.

An app that calls a query handler gets one answer, and sees a change only if it calls again. A live query keeps the answer current: the luna runs the query again after each write that could change it, and sends the app the new result.

Watch a query

An app can watch any handler with query: true of a public luna type. The List luna from the Quickstart has one, all.

import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: {
    items: table({ id: t.id(), text: t.string() }),
  },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      ctx.db.items.insert({ text });
    }),
    all: h({ query: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),
  }),
});

In the app, createClient from luna/client takes the URL and publishable key that luna dev writes to .env.local. client.luna names one luna by its type and key, and query watches one of its query handlers.

import { createClient } from "luna/client";
import type { List } from "../luna/lunas/list.ts";

const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });
const groceries = client.luna<typeof List>("List", "groceries");
const items = groceries.query("all");

const stop = items.subscribe(() => {
  const { status, data } = items.get();
  if (status === "ready") console.log(data?.map((item) => item.text));
});

subscribe runs your function on every change, and get returns the latest state. The client opens a connection to the luna when the first subscriber arrives. Add an item from anywhere, and the app logs the new list.

await groceries.mutate("add", { text: "milk" });

Know what makes a new result

The luna notes which tables each run of the query reads. After a write that changes one of them, it runs the query again for each app watching, and sends a result only when it differs from the last one.

  • A table read only through filters on exact values, such as where: { owner }, counts only when a changed row matched the filter, before or after the change.
  • Only the luna’s own tables count. A change in another luna does not run the query again.
  • The answer to a write reaches the app before the new results that write causes.
  • A table made with raw SQL as WITHOUT ROWID is not followed.

A result equal to the last one is not news. Your function does not run, and get returns the same object as before.

Read the state

get returns a QueryState. It is the same object until something changes, so a framework can compare it with ===.

Field Holds
status "loading" until the first result, "ready" once there is data, "error" when the first run failed
data The latest result, with the optimistic updates of this app’s pending writes laid over it
error A ConnectionError from the latest run that failed, with its code and message. data keeps the last good result, and the next good result clears it
stale true while data may be behind: the connection is down, or data is a copy saved by an earlier run of the app

To show a write in data before the luna confirms it, pass optimistic to mutate. Call lunas from TypeScript shows how.

Pass arguments

query takes the handler’s args as its second argument.

startingWith: h({ query: true, args: { prefix: t.string() } }, (ctx, { prefix }) =>
  ctx.db.items.find({ orderBy: "id" }).filter((item) => item.text.startsWith(prefix)),
),
const m = groceries.query("startingWith", { prefix: "m" });

Queries of the same handler with equal args, whatever the order of their keys, share one subscription and one result in the client.

Share one run between many apps

By default the luna runs a live query once for each app watching it, as that app’s connection, so the query can read ctx.caller. Mark a query shared when its result depends only on its args and the luna’s data. Apps that watch it with equal args then share one run after each write.

all: h({ query: true, shared: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),

Stay live through sleep and lost connections

An app watching a query does not keep the luna awake. The luna keeps its subscriptions while it sleeps, and runs them again when it wakes.

When the connection drops, data stays and stale turns true. The client reconnects by itself, waiting longer after each failure, up to 15 seconds, and subscribes again. The first new result clears stale.

A luna that closes the connection on purpose is not reconnected to, and each query’s error gives the reason. Open a connection explains closing.

Stop watching

Call the function subscribe returned.

stop();

A query nobody watches stays live and cached for 10 seconds, so a screen that comes back shows it at once. The connection closes once nothing has used it for as long. Set keepAliveMs in createClient to change both.

Know the limits

  • A handler without query: true cannot be watched. The luna refuses it with Invalid.
  • One app’s connection to one luna holds at most 128 live queries. The luna refuses more with Overloaded.

Next steps

Was this page helpful?