Live queries
A live query is defined on the server and read in the browser. When a write is committed to a table it read, every page showing it updates, with no reload.
Define one
// app/queries.ts
"use server";
import { live } from "simien:db";
import { db } from "@/simien/db";
export const latest = live(async () =>
db.posts.findMany({ where: { published: true }, orderBy: { createdAt: "desc" }, limit: 10 }),
);
It's a Server Function: the browser can call only the queries the app defines, never write its own.
Use it
On the server, it's the query:
// a Server Component
const posts = await latest();
In a client component, useQuery subscribes to it:
"use client";
import { useQuery } from "@/tana/live";
import { latest } from "./queries";
export function Latest({ initial }) {
const posts = useQuery(latest) ?? initial;
return <ul>{posts.map((post) => <li key={post.id}>{post.title}</li>)}</ul>;
}
useQuery(query, ...args) returns the latest result, or undefined until the first one arrives; pass the server-rendered value as a fallback, as above, so the page never flashes empty. Arguments are passed to the query.
The default template's counter works this way: open two tabs and click in one.
How it works
- Every table has a trigger that reports each committed write, whoever made it: the app, a migration, or
psql. A write that's rolled back reports nothing. - In dev,
simien devstreams those reports, and the app's dev server relays them to the browser at/__simien/changes. useQuerycalls the query again when one arrives. Of several answers in flight, an older one never replaces a newer one.
Limits today
- Dev only. Deployed apps get live queries with
simien deploy. - Re-runs on every write. A live query knows which tables it read, but the browser re-runs it after a write to any table; re-running only when its own tables change comes next.
- The same rights as a Server Action. Per-viewer access rules and cursors for long lists aren't decided yet.