Queries

Learn how to run one-shot queries and subscriptions, use the framework hooks and Suspense, and choose read durability.

One-shot queries

A one-shot query runs once against the database without subscribing to changes.

export async function readTodosOneshot(db: Db) {
return db.all(app.todos.where({ done: false }));
}

To read a single row, use db.one. It runs the query with a limit of one and resolves to the first matching row, or null if no row matches or you aren't allowed to read it.

export async function readTodo(db: Db, id: string) {
// Resolves to the first matching row, or null if no row matches or you can't read it
return db.one(app.todos.where({ id }));
}

Subscriptions

Subscribe to a query to receive updates whenever the underlying data changes.

export function subscribeTodos(db: Db, onCount: (count: number) => void) {
return db.subscribe(app.todos.where({ done: false }), (todos) => onCount(todos.length));
}

Composing queries

Queries are immutable and chainable. Each method returns a new query, so you can store a base and reuse it for different views without side effects.

// Store a base query and reuse it for different views.
const openTodos = app.todos.where({ done: false });
​
const byNewest = openTodos.orderBy("id", "desc");
const byTitle = openTodos.orderBy("title", "asc").limit(20);
const urgent = openTodos.where({ title: { contains: "urgent" } });

See Filters & Sorting for the full list of where operators, orderBy, limit, and offset.

Read durability

In browsers and React Native, queries and subscriptions read local-first by default: their first result waits briefly (up to 5 seconds) for the server while the client is online, and shows local data at once when it is offline. After that, local writes show instantly and remote updates stream in as they arrive. When you need a stronger guarantee for the first result, pass a tier option to fetch data from a different tier before returning.

In Node (a backend client, a script or a test) with a serverUrl, a read that names no tier is "remote": it waits for the server, and rejects while the server is unreachable. Catch that rejection, since an uncaught one ends a Node process, or pass tier: "local-first" to read local data.

Write waits distinguish local persistence from Core acceptance. Synchronization continues with either choice.

TierWhereWhat confirmation means
"local"This deviceSaved by the local persistence driver, without waiting for the network.
"global"CoreAuthorized and durably accepted by Core. Other clients receive updates through their subscriptions.

For background on how data flows between tiers, see How Sync Works.

Choosing a tier

Pass a read choice when you need to control whether the first result may use local knowledge — for example, when a user has just navigated to a page and a stale local snapshot would mislead them.

  • "local-first" uses cached local data and pending local writes immediately, while continuing to sync.
  • "remote" waits for Core-authorized query results and excludes pending local edits.

See Read tiers for pending-write behavior and how subscriptions change between offline and online operation. These are the only read tiers. Write waits use the separate durability tiers "local" and "global".

export async function readTodosAtRemoteTier(db: Db) {
return db.all(app.todos.where({ done: false }), { tier: ReadTier.Remote });
}
Remote subscriptions stay permission-scoped

Strict remote reads continue using Core-authorized state after the first result. Local-first reads can include cached data and optimistic writes; waiting for a write to reach Core does not change a separate subscription's read choice.

Waiting briefly for the server

A local-first read can wait a bounded time for the server before its first result. Pass firstLoadRemoteWaitMs:

const todos = await db.all(app.todos, {
tier: "local-first",
firstLoadRemoteWaitMs: 500,
});
db.subscribe(app.todos, onChange, {
tier: "local-first",
firstLoadRemoteWaitMs: 500,
});
const rows = useAll(app.todos, {
tier: "local-first",
firstLoadRemoteWaitMs: 500,
});
  • Only the initial load waits: a one-shot read, or a subscription's first callback. While the client looks online (its connection is live, or its connection attempt started less than 5 s ago), Jazz waits up to firstLoadRemoteWaitMs for the server's answer and shows that result, together with your own pending writes. If the server has not answered in time, it shows the local result.
  • It waits even when the local cache already has data, but never longer than the timeout. Use it to avoid showing a stale or empty snapshot on a fresh device.
  • It never waits offline, without a configured server, after db.disconnect(), while the connection is retrying, or when the connection drops during the wait: local data shows at once.
  • After the first result it behaves exactly like "local-first": your writes show immediately and remote changes show when they arrive.
  • Queries with an offset read the server's page while waiting, because a partly synced cache would apply the offset to the wrong rows. On timeout they show the cached page.
  • With an explicit tier: "local-first" the default is 0, plain "local-first". A browser or React Native read that names no tier defaults to 5000 when a server is configured; pass firstLoadRemoteWaitMs: 0 to show local data at once. TypeScript rejects the option on a "remote" read, which always waits for the server (plain JavaScript callers have it ignored).

Own writes

The read tier also determines how a subscription treats your own local writes:

  • "local-first" shows pending local writes using locally known data.
  • "local-first" with firstLoadRemoteWaitMs shows pending local writes exactly like "local-first", including in a first result that came from the server.
  • "remote" has no pending overlay: writes appear when reflected in the server's query scope.

See Durability Tiers for the full reference, including which APIs accept these options and how they compose.

Magic columns

See Edit Metadata for $createdBy, $createdAt and the other magic columns.

Framework hooks

Each framework has a reactive binding that re-renders when query results change. See Framework Patterns for side-by-side examples.

FrameworkAPINotes
React/ExpouseAll(query)Returns { data, isLoading, error }
VueuseAll(query)Returns { data, isLoading, error } refs
Sveltenew QuerySubscription(query)Exposes reactive .current / .isLoading / .error
SoliduseAll(() => ({ query }))Returns { data, isLoading, error }

Each one has a single-row variant, covered in Reading one row: useOne in React, Expo, Vue and Solid, and QuerySubscriptionOne in Svelte.

The loading state

useAll's data field (or Vue's data ref and Svelte's QuerySubscription.current) are undefined until the first result arrives from the requested tier. After that, the value is an array — empty ([]) if no rows match, or populated with the requested data.

const allTodos = useAll(app.todos);
// `allTodos.data` is `undefined` while loading the first result (and `allTodos.isLoading` is `true`).
// `allTodos.data` is `[]` when loaded but empty
Note

You're unlikely to see data: undefined in practice unless you're awaiting a more durable tier. Local storage reads are effectively instant and resolve to [] if no data exists yet.

Reading one row

For detail pages, use useOne (or QuerySubscriptionOne in Svelte). It takes the same query and options as useAll, limits it to one row, and gives you that row instead of an array:

  • undefined while the first result is loading, and also when the query failed (see error) or was skipped.
  • null once loaded, if no row matches or you aren't allowed to read it.
  • The row itself otherwise, with any relations you asked for in include(...).
export function TodoDetail({ id }: { id: string }) {
const { data: todo, error } = useOne(app.todos.where({ id }).include({ project: true }));
// `todo` is `undefined` while loading, `null` if no row matches or you can't read it
​
if (error) return <p>Couldn't load this todo.</p>;
if (todo === undefined) return <p>Loading…</p>;
if (todo === null) return <p>Todo not found.</p>;
​
return (
<article>
<h1>{todo.title}</h1>
{todo.project && <p>In {todo.project.name}</p>}
</article>
);
}

Like useAll, useOne accepts undefined instead of a query to skip evaluation. React and Vue also have useOneSuspense, which waits for the first result instead of reporting a loading state (see React Suspense and Transitions).

Fine-grained updates

Vue's useAll, Svelte's QuerySubscription, and Solid's useAll reconcile new query results into the existing reactive array in place rather than swapping the reference. When an upstream change touches a single row, only that row's affected fields write into the reactive proxy, so $effect (Svelte), Solid computations/effects, and watch / template bindings (Vue) only re-fire for components that depend on the fields that actually changed.

In practice this means:

  • Adding, removing, or reordering rows updates the array structure only — untouched row objects keep their identity, so {#each items as item (item.id)} and <TransitionGroup> keyed renders are stable.
  • Editing a single field on one row writes only that field — sibling rows do not re-render, and per-row components that read other fields stay quiet.
  • Vue's useAll returns { data, isLoading, error, db }, where data is a deep Ref (not a shallowRef), so per-field reactivity composes with the rest of your component tree without manual unwrapping.
  • Because the array is updated in place, data.value stays the same array: in Vue, watch(data, cb) doesn't fire on inserts, deletes or edits. Pass { deep: true }, or watch what you need, such as () => data.value?.length. Template bindings and computed track it on their own.
  • React and Solid return { data, isLoading, error, db }; React returns a fresh data array each tick, while Solid's store keeps fine-grained dependency tracking for fields that changed.

React's granularity benefit comes from React's diffing, not from in-place reconciliation.

Conditional queries

Pass undefined instead of a query to skip evaluation. This is useful when building dynamic queries.

const [filter, setFilter] = useState<string | null>(null);
const { data: filtered } = useAll(
filter ? app.todos.where({ title: { contains: filter } }) : undefined,
);

React Suspense and Transitions

useAllSuspense is a React-specific variant that suspends instead of returning a loading state, keeping the previous result visible while the next one loads. It returns { data, db }.

App.tsx
export function ConcurrentTodoList() {
const db = useDb();
const [title, setTitle] = useState("");
const [filterTitle, setFilterTitle] = useState("");
const [showDoneOnly, setShowDoneOnly] = useState(false);
const [page, setPage] = useState(0);
const [isPending, startTransition] = useTransition();
const deferredFilterTitle = useDeferredValue(filterTitle);
​
let query = app.todos
.orderBy("id", "desc")
.limit(25)
.offset(page * 25);
​
if (deferredFilterTitle.trim()) {
query = query.where({ title: { contains: deferredFilterTitle.trim() } });
}
if (showDoneOnly) {
query = query.where({ done: true });
}
​
const isLoading = isPending || deferredFilterTitle !== filterTitle;
​
function updatePage(nextPage: number) {
startTransition(() => {
setPage(nextPage);
});
}
​
function handleFilterChange(e: React.ChangeEvent<HTMLInputElement>) {
setFilterTitle(e.target.value);
startTransition(() => {
setPage(0);
});
}
​
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const trimmedTitle = title.trim();
​
if (!trimmedTitle) {
return;
}
​
await db.insert(app.todos, { title: trimmedTitle, done: false });
setTitle("");
}
​
return (
<>
<form onSubmit={(e) => void handleSubmit(e)}>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="What needs to be done?"
required
/>
<button type="submit">Add</button>
</form>
​
<div>
<input
type="text"
value={filterTitle}
onChange={handleFilterChange}
placeholder="Filter by title (contains)"
aria-label="Filter by title"
/>
<label>
<input
type="checkbox"
checked={showDoneOnly}
onChange={(e) => setShowDoneOnly(e.target.checked)}
/>
Done only
</label>
</div>
​
<Suspense fallback={<p>Loading todos...</p>}>
<div style={{ opacity: isLoading ? 0.5 : 1, transition: "opacity 0.2s" }}>
<ConcurrentTodoResults query={query} page={page} onPageChange={updatePage} />
</div>
</Suspense>
</>
);
}

useOneSuspense does the same for a single row. Its data is the row, or null if no row matches or you aren't allowed to read it.

export function TodoDetailPage({ id }: { id: string }) {
return (
<Suspense fallback={<p>Loading…</p>}>
<TodoTitle id={id} />
</Suspense>
);
}
​
function TodoTitle({ id }: { id: string }) {
const { data: todo } = useOneSuspense(app.todos.where({ id }));
return <h1>{todo ? todo.title : "Todo not found"}</h1>;
}