> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a reactive chat app

> Write a table, a mutation and a query, then watch the messages from React

Start with [the default React/Vite app](https://docs.bijection.com/start/quickstart.md). Add a messages
table, a bounded query and an insert mutation, and place them in the app
tree.

```ts bijection/messages.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, query, role, t, table } from "@bijectionhq/bijection";

export const messages = table({ body: t.string, at: t.instant }, { index: [["at"]] });

export const send = mutation(
  { allow: [role.anyone], args: { body: t.string } },
  (ctx, { body }) => ctx.insert(messages, { body, at: ctx.frame.now.entry }),
);

export const list = query({ allow: [role.anyone] }, (ctx) =>
  ctx.list(messages.by("at").descending().first(50)),
);
```

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app } from "@bijectionhq/bijection";
import * as messages from "./messages";

export default app({ messages });
```

The functions are exposed at `messages.send` and `messages.list`. Connect and create typed references from the app tree:

```ts src/client.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api, connect } from "@bijectionhq/bijection/client";
import type App from "../bijection/app";

export const app = api<typeof App>();
export const client = connect("https://chat.example.com", { contract: "discover" });
```

In React, watch the list and hold the mutation:

```tsx src/Chat.tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useMutation, useWatch } from "@bijectionhq/bijection/react";
import { app } from "./client";

export function Chat() {
  const messages = useWatch(app.messages.list, {});
  const send = useMutation(app.messages.send);
  if (messages === undefined) return <p>Loading…</p>;
  if (!messages.ok) return <p>{messages.message}</p>;
  return (
    <form onSubmit={(event) => {
      event.preventDefault();
      const body = new FormData(event.currentTarget).get("body");
      if (typeof body === "string") void send({ body });
    }}>
      <ul>{messages.value.map((m) => <li key={m.id}>{m.body}</li>)}</ul>
      <input name="body" />
    </form>
  );
}
```

Render it inside `<Bijection client={client}>`. Open a second tab to see a
new message arrive in the watch.

For private channels, give the table a `label`, give the functions an
`under` and an `allow` of your own roles, and [grant](https://docs.bijection.com/access/grants.md) those
roles.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.