# Comment thread

> A record's comments with their authors and a form to add one, kept current after each write.

- Block: [comments](https://bettersupabase.com/blocks/comments.md)
- Kind: component
- Hook: `useComments` from `@/hooks/use-comments`
- Page: https://bettersupabase.com/recipes/comment-thread

## Install the block

```bash
npx better-supabase add comments
```

## Web (Next.js)

Add the shadcn components:

```bash
npx shadcn add button field skeleton textarea
```

Add the glue from the better-supabase registry:

```bash
npx shadcn add @better-supabase/use-comments
```

From `apps/examples/nextjs/src/features/customers/components/comment-thread.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/nextjs/src/features/customers/components/comment-thread.tsx):

```tsx
"use client";

import type { SubmitEvent } from "react";

import { useErrorMessage } from "better-supabase/react";
import { useExtracted, useFormatter } from "next-intl";
import { useId, useOptimistic, useState, useTransition } from "react";

import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { useComments } from "@/hooks/use-comments";

/**
 * A record's comments, oldest first, through the browser client. `subject` is
 * any type in `config.recordTypes`, such as a customer or a project.
 */
export function CommentThread({
  subject,
  authors,
  canComment,
}: {
  subject: { readonly type: string; readonly id: string };
  /** Display names by user id. */
  authors: Readonly<Record<string, string>>;
  canComment: boolean;
}) {
  const t = useExtracted("customers");
  const format = useFormatter();
  const errorMessage = useErrorMessage();
  const fieldId = useId();
  const [body, setBody] = useState("");
  const [pending, startTransition] = useTransition();

  const { comments, error, add } = useComments({ subject });

  const visible = comments?.filter((comment) => !comment.deletedAt);

  // The comment shows at once and settles when the server's list arrives.
  const [sending, addPending] = useOptimistic<string | undefined, string>(
    undefined,
    (_current, text) => text,
  );

  const submit = (event: SubmitEvent<HTMLFormElement>) => {
    event.preventDefault();
    const text = body.trim();

    if (!text) {
      return;
    }

    startTransition(async () => {
      addPending(text);

      if ((await add({ body: text })).ok) {
        setBody("");
      }
    });
  };

  return (
    <div className="flex flex-col gap-6">
      {visible === undefined ? (
        <Skeleton className="h-16" />
      ) : visible.length === 0 && sending === undefined ? (
        <p className="text-sm text-muted-foreground">{t("No comments yet.")}</p>
      ) : (
        <ol className="flex flex-col gap-4" data-testid="comments">
          {visible.map((comment) => (
            <li key={comment.id} className="flex flex-col gap-1">
              <p className="text-sm">
                <span className="font-medium">
                  {(comment.authorId && authors[comment.authorId]) ??
                    t("Someone")}
                </span>{" "}
                <span className="text-xs text-muted-foreground">
                  {format.dateTime(
                    (comment.sentAt ?? comment.createdAt).epochMilliseconds,
                    { dateStyle: "medium", timeStyle: "short" },
                  )}
                </span>
              </p>
              <p className="text-sm whitespace-pre-wrap">{comment.body}</p>
            </li>
          ))}
          {sending === undefined ? null : (
            <li
              className="text-sm whitespace-pre-wrap text-muted-foreground"
              aria-busy
            >
              {sending}
            </li>
          )}
        </ol>
      )}
      {canComment ? (
        <form onSubmit={submit} className="flex flex-col gap-3">
          <Field data-invalid={error ? true : undefined}>
            <FieldLabel htmlFor={`${fieldId}-comment-body`} className="sr-only">
              {t("Comment")}
            </FieldLabel>
            <Textarea
              id={`${fieldId}-comment-body`}
              value={body}
              onChange={(event) => {
                setBody(event.target.value);
              }}
              placeholder={t("Write a comment")}
              required
              maxLength={4000}
              rows={3}
            />
            {error ? <FieldError>{errorMessage(error)}</FieldError> : null}
          </Field>
          <Button type="submit" size="sm" disabled={pending}>
            {t("Comment")}
          </Button>
        </form>
      ) : null}
    </div>
  );
}
```

## Native (Expo)

The snippet uses `ActivityIndicator`, `Button`, `FlatList`, `Text`, `TextInput`, `View` from `react-native`, so it needs no styling library.

Add the glue from the better-supabase registry:

```bash
npx shadcn add @better-supabase/use-comments
```

From `apps/examples/expo-powersync/src/components/comment-thread.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/expo-powersync/src/components/comment-thread.tsx):

```tsx
import { useState } from "react";
import {
  ActivityIndicator,
  Button,
  FlatList,
  Text,
  TextInput,
  View,
} from "react-native";

import { useComments } from "../hooks/use-comments";

/** A customer's comments, oldest first, with a box to add one. */
export function CommentThread({ customerId }: { readonly customerId: string }) {
  const [body, setBody] = useState("");
  const [pending, setPending] = useState(false);

  const { comments, error, add } = useComments({
    subject: { type: "customer", id: customerId },
  });

  const submit = async () => {
    const text = body.trim();

    if (!text) {
      return;
    }

    setPending(true);

    try {
      if ((await add({ body: text })).ok) {
        setBody("");
      }
    } catch (error) {
      setPending(false);
      throw error;
    }

    setPending(false);
  };

  if (comments === undefined) {
    return <ActivityIndicator />;
  }

  return (
    <View style={{ flex: 1, gap: 12 }}>
      <FlatList
        data={comments.filter((comment) => !comment.deletedAt)}
        keyExtractor={(comment) => comment.id}
        ListEmptyComponent={<Text>No comments yet.</Text>}
        renderItem={({ item }) => (
          <View style={{ paddingVertical: 8 }}>
            <Text style={{ color: "#737373", fontSize: 12 }}>
              {(item.sentAt ?? item.createdAt).toLocaleString()}
            </Text>
            <Text>{item.body}</Text>
          </View>
        )}
      />
      {error ? <Text style={{ color: "#b91c1c" }}>{error.message}</Text> : null}
      <TextInput
        value={body}
        onChangeText={setBody}
        placeholder="Write a comment"
        multiline
        maxLength={4000}
        style={{ borderWidth: 1, borderRadius: 8, padding: 8, minHeight: 64 }}
      />
      <Button
        title="Comment"
        disabled={pending || !body.trim()}
        onPress={() => void submit()}
      />
    </View>
  );
}
```

## Prompt

Paste one of these into a coding agent to build the recipe in your app.

### Web

```text
Build "Comment thread" in a React web app that uses shadcn/ui components. A record's comments with their authors and a form to add one, kept current after each write.

It uses the better-supabase `comments` block (Comments). It calls the hook `useComments` from `@/hooks/use-comments`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add comments` and apply the migration.
2. Add the shadcn components the recipe uses: `npx shadcn add button field skeleton textarea`.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-comments`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useComments` from `@/hooks/use-comments`, starting from the recipe's snippet (`apps/examples/nextjs/src/features/customers/components/comment-thread.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it calls the same hook, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/comment-thread.md
- Block docs: https://bettersupabase.com/docs/blocks/comments
```

### Native

```text
Build "Comment thread" in a React Native app built with Expo. A record's comments with their authors and a form to add one, kept current after each write.

It uses the better-supabase `comments` block (Comments). It calls the hook `useComments` from `@/hooks/use-comments`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add comments` and apply the migration.
2. The recipe uses `ActivityIndicator`, `Button`, `FlatList`, `Text`, `TextInput`, `View` from `react-native`, so it needs no extra UI library. Use the app's own components if it has them.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-comments`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useComments` from `@/hooks/use-comments`, starting from the recipe's snippet (`apps/examples/expo-powersync/src/components/comment-thread.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it calls the same hook, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/comment-thread.md
- Block docs: https://bettersupabase.com/docs/blocks/comments
```
