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

luna/react

React hooks over the app client, for live queries, writes, connections, streams and indexes.

luna/react gives React components the app client as hooks. Each hook re-renders its component when what it reads changes.

import { createClient } from "luna/client";
import { LunaProvider, useLuna, useQuery } from "luna/react";
import type { List } from "../luna/lunas/list.ts";

const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });

function Groceries() {
  const list = useLuna<typeof List>("List", "groceries");
  const { data } = useQuery(list, "all");
  return <ul>{data?.map((i) => <li key={i.id}>{i.text}</li>)}</ul>;
}

export function App() {
  return <LunaProvider client={client}><Groceries /></LunaProvider>;
}

Reference

PropType
LunaProvider?(props: { client: LunaClient; children?: ReactNode }) => ReactNode

Gives a client to every hook below it.

Type(props: { client: LunaClient; children?: ReactNode }) => ReactNode
useClient()?() => LunaClient

The provider's client. Throws without a LunaProvider above.

Type() => LunaClient
useLuna(type, ...key)?(type: string, ...key: (string | number)[]) => LunaHandle

A luna, the same handle for as long as its type and key stay the same.

Type(type: string, ...key: (string | number)[]) => LunaHandle
useQuery(luna, handler, args)?QueryState<R>

A live query of a query handler. Pass null as args to skip it for now.

TypeQueryState<R>
useMutation(luna, handler, optimistic)?(args?) => Promise<R>

A function that calls a handler. optimistic is (local, args) => void.

Type(args?) => Promise<R>
useConnection(luna)?ConnectionStatus

The connection's state: "connecting", "open", "reconnecting" or "closed".

TypeConnectionStatus
useStream(luna, name, opts)?StreamState<T>

A stream of the luna read as it grows, without keeping the luna awake. opts is StreamOptions.

TypeStreamState<T>
useIndex(name, partition)?IndexHandle

One partition of an index, the same handle for as long as its name and partition stay the same.

TypeIndexHandle
useIndexQuery(index, read, opts)?QueryState<...>

A live read of an index: "find", "count", "groupBy", "search" or "nearest". Pass null as opts to skip it for now.

TypeQueryState<...>

QueryState, StreamState, StreamOptions and ConnectionStatus are on the LunaHandle page. The index reads and their options are on the IndexHandle page.

Good to know

  • useQuery and useIndexQuery compare their arguments by value. New arguments make a new query, and equal ones keep the old.
  • A skipped query reports the loading status and opens no connection.
  • A result equal to the last one does not re-render the component.
  • After a component unmounts, its query stays live for the client’s keepAliveMs, then ends.
  • The optimistic update of useMutation runs over the latest confirmed values each time they change, until the write is in. If the write fails, what it showed is rolled back and the promise rejects.
  • react 18 or later is a peer dependency of the SDK.

Examples

Add an item that shows at once

import { useLuna, useMutation } from "luna/react";
import type { List } from "../luna/lunas/list.ts";

export function AddItem() {
  const list = useLuna<typeof List>("List", "groceries");
  const add = useMutation(list, "add", (local, { text }) => {
    local.update(list.query("all"), (old) => [...old, { id: -1, text }]);
  });
  return <button onClick={() => add({ text: "milk" })}>Add milk</button>;
}

Show when the app is offline

import { useConnection, useLuna } from "luna/react";

export function Status() {
  const status = useConnection(useLuna("List", "groceries"));
  return status === "open" ? null : <p>Reconnecting</p>;
}

Show a stream as it grows

import { useLuna, useStream } from "luna/react";

export function Said() {
  const room = useLuna("Room", "lobby");
  const { entries } = useStream<{ text: string }>(room, "said", { limit: 50 });
  return <ul>{entries.map((e, i) => <li key={i}>{e.text}</li>)}</ul>;
}

Search an index as you type

import { useIndex, useIndexQuery } from "luna/react";
import type { BoardCards } from "../luna/lunas/board-cards.ts";

export function Search({ text }: { text: string }) {
  const cards = useIndex<typeof BoardCards>("BoardCards", "b1");
  const { data } = useIndexQuery(cards, "search", text ? { text, prefix: true } : null);
  return <ul>{data?.map((h, i) => <li key={i}>{h.row.title}</li>)}</ul>;
}

An empty box skips the search.

Was this page helpful?