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

Use Luna with React

Show a luna's data in React components that re-render when it changes, and show writes before Luna confirms them.

A component that shows a luna’s data has to re-render each time the data changes, and a click should show its effect at once. The hooks in luna/react do both on top of the client from luna/client.

Provide the client

Create one client outside any component, and put it in a LunaProvider at the top of the app.

import { createClient } from "luna/client";
import { LunaProvider } from "luna/react";
import { Groceries } from "./groceries.tsx";

const client = createClient({
  url: import.meta.env.VITE_LUNA_URL,
  key: import.meta.env.VITE_LUNA_KEY,
});

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

When the folder’s package.json uses Vite, the CLI writes the URL and key to .env.local a second time as VITE_LUNA_URL and VITE_LUNA_KEY. With Next.js the names start with NEXT_PUBLIC_, and with Expo they start with EXPO_PUBLIC_.

Show a live query

useLuna returns the handle of one luna, and stays the same object while its type and key stay the same. useQuery subscribes to a query handler and re-renders the component when the result changes.

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

export function Groceries() {
  const list = useLuna<typeof List>("List", "groceries");
  const { status, data, error } = useQuery(list, "all");

  if (status === "loading") return <p>Loading</p>;
  if (status === "error") return <p>{error?.message}</p>;
  return <ul>{data?.map((item) => <li key={item.id}>{item.text}</li>)}</ul>;
}

status is loading until the first result, ready once there is data, and error if the first run failed. While the connection is down, stale is true and data keeps the last result. Subscribe to a query explains what brings a new result.

Pass null as the arguments to skip a query for now, such as while a search box is empty.

Show a write at once

useMutation returns a function that calls a handler. Its third argument is an optimistic update: what queries show until Luna confirms the write.

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

export function Groceries() {
  const list = useLuna<typeof List>("List", "groceries");
  const { data } = useQuery(list, "all");
  const add = useMutation(list, "add", (local, { text }) => {
    local.update(list.query("all"), (items) => [...items, { id: -1, text }]);
  });

  return (
    <>
      <ul>{data?.map((item) => <li key={item.id}>{item.text}</li>)}</ul>
      <button onClick={() => add({ text: "milk" })}>Add milk</button>
    </>
  );
}

The new item shows at once with a stand-in id. When a live result that includes the write arrives, it takes the item’s place, and the item never shows twice. If the call fails, the update is removed and the promise add returned rejects.

Show the connection

useConnection returns connecting, open, reconnecting or closed, and re-renders when it changes.

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

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

Follow a stream

useStream reads one of a luna’s streams as it grows, without keeping the luna awake. It returns the entries read so far, oldest first.

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

export function Log({ room }: { room: string }) {
  const { entries } = useStream<{ text: string }>(useLuna("Room", room), "log", { offset: "now" });
  return <ul>{entries.map((e, i) => <li key={i}>{e.text}</li>)}</ul>;
}

offset is -1 to start from the oldest entry, the default, or now to start from the end. Follow a stream from an app covers the rest.

Read an index

useIndex returns one partition of an index, and useIndexQuery reads it live with find, count, groupBy, search or nearest.

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

export function Search({ board, text }: { board: string; text: string }) {
  const search = useIndex<typeof BoardSearch>("BoardSearch", board);
  const { data } = useIndexQuery(search, "search", text ? { text, prefix: true } : null);
  return <ul>{data?.map(({ row }) => <li key={row.card}>{row.text}</li>)}</ul>;
}

The null skips the search while text is empty. The index needs an onBeforeConnect that lets apps read it, as Query across lunas shows.

Next steps

Was this page helpful?