# Members table

> An organization's members with their roles, where a role change shows at once and a member can be removed.

- Block: [organizations](https://bettersupabase.com/blocks/organizations.md)
- Kind: component
- Hook: `useMembers` from `@/hooks/use-organizations`
- Page: https://bettersupabase.com/recipes/members-table

## Install the block

```bash
npx better-supabase add organizations
```

## Web (Next.js)

Add the shadcn components:

```bash
npx shadcn add avatar badge button empty input select
```

Add the glue from the better-supabase registry:

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

From `apps/examples/nextjs/src/features/members/components/member-table.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/nextjs/src/features/members/components/member-table.tsx):

```tsx
"use client";

import type { CellContext, ColumnDef } from "@tanstack/react-table";

import { useTable } from "@tanstack/react-table";
import { DbException } from "better-supabase";
import { useErrorMessage } from "better-supabase/react";
import { UserMinusIcon } from "lucide-react";
import { useExtracted, useFormatter } from "next-intl";
import { createContext, use, useCallback, useMemo, useState } from "react";
import * as v from "valibot";

import type { ReadOnlyGridFeatures } from "@/components/reui/data-grid/data-grid";
import type { Member } from "@/features/organization/organization-queries";

import {
  DataGrid,
  DataGridContainer,
} from "@/components/reui/data-grid/data-grid";
import { readOnlyGridFeatures } from "@/components/reui/data-grid/data-grid-features-read-only";
import { DataGridScrollArea } from "@/components/reui/data-grid/data-grid-scroll-area";
import { DataGridTable } from "@/components/reui/data-grid/data-grid-table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Empty,
  EmptyContent,
  EmptyDescription,
  EmptyHeader,
  EmptyTitle,
} from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  loadMembers,
  memberChanged,
} from "@/features/organization/organization-actions";
import { useRoleLabel } from "@/features/organization/use-role-label";
import { ViewAsMemberButton } from "@/features/support/components/view-as-member-button";
import { RoleBadge } from "@/features/user/components/role-badge";
import { useMembers } from "@/hooks/use-organizations";
import { Link } from "@/i18n/navigation";
import { Role } from "@/lib/claims";
import { initials } from "@/lib/initials";
import { organizationsConfig } from "@/lib/supabase/blocks/slices";
import { toast } from "@/lib/toast";
import { useSearchParam } from "@/lib/url-filters";

async function getOrganizationMembers(): Promise<readonly Member[]> {
  const result = await loadMembers({});

  if (!result.ok) {
    throw new DbException(result.error);
  }

  return result.data;
}

/** A team as the members table shows it: its name and who is on it. */
export interface MemberTeam {
  readonly id: string;
  readonly name: string;
  readonly memberIds: readonly string[];
}

type MemberRow = Member & {
  readonly teams: readonly MemberTeam[];
  readonly you: boolean;
  /** The roles the caller may pick here, empty when the role is fixed. */
  readonly roleChoices: readonly Role[];
  readonly removable: boolean;
  /** The caller may start a support session on this member. */
  readonly viewable: boolean;
  readonly busy: boolean;
};

type MemberCell = CellContext<ReadOnlyGridFeatures, MemberRow>;

const ALL_ROLES = "all";

function MemberCellView({ row }: MemberCell) {
  const t = useExtracted("members");
  const member = row.original;

  return (
    <div className="flex items-center gap-3">
      <Avatar className="size-8">
        {member.avatarUrl ? (
          <AvatarImage src={member.avatarUrl} alt="" />
        ) : null}
        <AvatarFallback>{initials(member.name, member.email)}</AvatarFallback>
      </Avatar>
      <div className="grid min-w-0 leading-tight">
        <Link
          href={`/settings/members/${member.userId}`}
          prefetch
          className="truncate font-medium hover:underline"
        >
          {member.name ?? member.email}
          {member.you ? (
            <span className="font-normal text-muted-foreground">
              {" "}
              ({t("you")})
            </span>
          ) : null}
        </Link>
        <span className="truncate text-xs text-muted-foreground">
          {member.email}
        </span>
      </div>
    </div>
  );
}

function TeamsCell({ row }: MemberCell) {
  const { teams } = row.original;

  if (teams.length === 0) {
    return <span className="text-muted-foreground">–</span>;
  }

  return (
    <div className="flex flex-wrap gap-1">
      {teams.map((team) => (
        <Badge key={team.id} variant="outline">
          {team.name}
        </Badge>
      ))}
    </div>
  );
}

function JoinedCell({ row }: MemberCell) {
  const format = useFormatter();
  const { joinedAt } = row.original;

  return (
    <span className="text-muted-foreground tabular-nums">
      {joinedAt
        ? format.dateTime(new Date(joinedAt), { dateStyle: "medium" })
        : "–"}
    </span>
  );
}

interface MemberActions {
  readonly changeRole: (member: Member, role: Role) => Promise<void>;
  readonly removeMember: (member: Member) => Promise<void>;
  readonly selected: ReadonlySet<string>;
  readonly toggle: (userId: string, on: boolean) => void;
}

const MemberActionsContext = createContext<MemberActions | null>(null);

function useMemberActions(): MemberActions {
  const actions = use(MemberActionsContext);

  if (actions === null) {
    throw new Error("Render member cells inside <MemberTable>.");
  }

  return actions;
}

function SelectCell({ row }: MemberCell) {
  const t = useExtracted("members");
  const { selected, toggle } = useMemberActions();
  const member = row.original;

  if (member.roleChoices.length === 0) {
    return null;
  }

  return (
    <Checkbox
      checked={selected.has(member.userId)}
      disabled={member.busy}
      aria-label={t("Select {name}", {
        name: member.name ?? member.email ?? "",
      })}
      onCheckedChange={(checked) => {
        toggle(member.userId, checked);
      }}
    />
  );
}

function RoleCell({ row }: MemberCell) {
  const t = useExtracted("members");
  const roleLabel = useRoleLabel();
  const { changeRole } = useMemberActions();
  const member = row.original;

  if (member.roleChoices.length === 0) {
    return <RoleBadge role={member.role} />;
  }

  const items = member.roleChoices.map((role) => ({
    value: role,
    label: roleLabel(role),
  }));

  return (
    <Select
      value={member.role}
      items={items}
      disabled={member.busy}
      onValueChange={(value) => {
        if (v.is(Role, value)) {
          void changeRole(member, value);
        }
      }}
    >
      <SelectTrigger size="sm" className="w-32" aria-label={t("Role")}>
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {items.map((item) => (
          <SelectItem key={item.value} value={item.value}>
            {item.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

function ActionsCell({ row }: MemberCell) {
  const t = useExtracted("members");
  const { removeMember } = useMemberActions();
  const member = row.original;

  if (!member.removable && !member.viewable) {
    return null;
  }

  return (
    <div className="flex items-center gap-1">
      {member.viewable ? (
        <ViewAsMemberButton
          userId={member.userId}
          name={member.name ?? member.email ?? ""}
        />
      ) : null}
      {member.removable ? (
        <Button
          variant="ghost"
          size="icon-sm"
          disabled={member.busy}
          aria-label={t("Remove {name}", {
            name: member.name ?? member.email ?? "",
          })}
          onClick={() => {
            void removeMember(member);
          }}
        >
          <UserMinusIcon />
        </Button>
      ) : null}
    </div>
  );
}

/**
 * The organization's members in a ReUI data grid, with a search and a role
 * filter. The server renders the rows; a role change shows at once and goes
 * through `update_member_role` in the browser.
 */
export function MemberTable({
  organizationId,
  initial,
  teams,
  currentUserId,
  assignable,
  canUpdateRole,
  canRemove,
  canViewAs,
}: {
  organizationId: string;
  initial: readonly Member[];
  teams: readonly MemberTeam[];
  currentUserId: string;
  assignable: readonly Role[];
  canUpdateRole: boolean;
  canRemove: boolean;
  canViewAs: boolean;
}) {
  const t = useExtracted("members");
  const roleLabel = useRoleLabel();
  const errorMessage = useErrorMessage();
  const [search, setSearch] = useSearchParam();

  const [roleFilter, setRoleFilter] = useState<Role | typeof ALL_ROLES>(
    ALL_ROLES,
  );

  const { members, pending, setRole, setRoles, remove } = useMembers({
    organizationId,
    load: getOrganizationMembers,
    initial,
    schema: organizationsConfig.api,
    onChanged: async ({ userId }) => {
      await memberChanged({ userId });
    },
  });

  const filterItems = [
    { value: ALL_ROLES, label: t("All roles") },
    ...Role.options.map((role) => ({ value: role, label: roleLabel(role) })),
  ];

  // Nobody changes their own role or an owner's here; ownership moves by transfer.
  const editable = (member: Member) =>
    member.userId !== currentUserId &&
    member.role !== "owner" &&
    assignable.includes(member.role);

  const changeRole = useCallback(
    async (member: Member, role: Role) => {
      const result = await setRole({ userId: member.userId, role });

      if (result.ok) {
        toast.success(t("Role updated"));
      } else {
        toast.error(errorMessage(result.error));
      }
    },
    [setRole, t, errorMessage],
  );

  const removeMember = useCallback(
    async (member: Member) => {
      const result = await remove(member.userId);

      if (result.ok) {
        toast.success(t("Member removed"));
      } else {
        toast.error(errorMessage(result.error));
      }
    },
    [remove, t, errorMessage],
  );

  const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
  const [bulkRole, setBulkRole] = useState<Role | null>(null);
  const [applying, setApplying] = useState(false);

  const toggle = useCallback((userId: string, on: boolean) => {
    setSelected((current) => {
      const next = new Set(current);

      if (on) {
        next.add(userId);
      } else {
        next.delete(userId);
      }

      return next;
    });
  }, []);

  const actions = useMemo(
    () => ({ changeRole, removeMember, selected, toggle }),
    [changeRole, removeMember, selected, toggle],
  );

  const columns: ColumnDef<ReadOnlyGridFeatures, MemberRow>[] = [
    ...(canUpdateRole
      ? [{ id: "select", header: "", cell: SelectCell, size: 40 }]
      : []),
    { id: "member", header: t("Member"), cell: MemberCellView, size: 280 },
    { accessorKey: "role", header: t("Role"), cell: RoleCell, size: 150 },
    { id: "teams", header: t("Teams"), cell: TeamsCell, size: 200 },
    {
      accessorKey: "joinedAt",
      header: t("Joined"),
      cell: JoinedCell,
      size: 140,
    },
    { id: "actions", header: "", cell: ActionsCell, size: 56 },
  ];

  const needle = search.trim().toLowerCase();
  const all = members ?? initial;

  const data: MemberRow[] = all
    .filter(
      (member) =>
        (roleFilter === ALL_ROLES || member.role === roleFilter) &&
        (needle === "" ||
          [member.name, member.email].some((text) =>
            text?.toLowerCase().includes(needle),
          )),
    )
    .map((member) => ({
      ...member,
      teams: teams.filter((team) => team.memberIds.includes(member.userId)),
      you: member.userId === currentUserId,
      roleChoices: canUpdateRole && editable(member) ? assignable : [],
      removable: canRemove && editable(member),
      viewable: canViewAs && member.userId !== currentUserId,
      busy: pending.includes(member.userId),
    }));

  const table = useTable({
    features: readOnlyGridFeatures,
    columns,
    data,
    getRowId: (row) => row.userId,
  });

  const applyBulkRole = async () => {
    if (!bulkRole) {
      return;
    }

    setApplying(true);

    const result = await setRoles({ userIds: [...selected], role: bulkRole });
    let changed = 0;

    if (result.ok) {
      changed = result.data.succeeded.length;

      for (const failure of result.data.failed) {
        toast.error(errorMessage(failure.error));
      }
    } else {
      toast.error(errorMessage(result.error));
    }

    setApplying(false);
    setSelected(new Set());

    if (changed > 0) {
      toast.success(
        t("{count, plural, one {# role updated} other {# roles updated}}", {
          count: changed,
        }),
      );
    }
  };

  const clearFilters = () => {
    setSearch("");
    setRoleFilter(ALL_ROLES);
  };

  return (
    <MemberActionsContext value={actions}>
      <div className="flex flex-col gap-3">
        <div className="flex flex-wrap items-center gap-2">
          <Input
            type="search"
            className="w-56"
            value={search}
            placeholder={t("Search members")}
            aria-label={t("Search members")}
            onChange={(event) => {
              setSearch(event.target.value);
            }}
          />
          <Select
            value={roleFilter}
            items={filterItems}
            onValueChange={(value) => {
              setRoleFilter(v.is(Role, value) ? value : ALL_ROLES);
            }}
          >
            <SelectTrigger size="sm" className="w-36" aria-label={t("Role")}>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {filterItems.map((item) => (
                <SelectItem key={item.value} value={item.value}>
                  {item.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        {selected.size > 0 ? (
          <div
            className="flex flex-wrap items-center gap-2 rounded-lg border bg-muted/40 p-2"
            data-testid="members-bulk-bar"
          >
            <span className="text-sm">
              {t("{count, number} selected", { count: selected.size })}
            </span>
            <Select
              value={bulkRole}
              items={assignable.map((role) => ({
                value: role,
                label: roleLabel(role),
              }))}
              onValueChange={(value) => {
                setBulkRole(v.is(Role, value) ? value : null);
              }}
            >
              <SelectTrigger
                size="sm"
                className="w-40"
                aria-label={t("New role")}
              >
                <SelectValue placeholder={t("Change role to")} />
              </SelectTrigger>
              <SelectContent>
                {assignable.map((role) => (
                  <SelectItem key={role} value={role}>
                    {roleLabel(role)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button
              size="sm"
              disabled={!bulkRole || applying}
              onClick={() => {
                void applyBulkRole();
              }}
            >
              {t("Apply")}
            </Button>
            <Button
              size="sm"
              variant="ghost"
              disabled={applying}
              onClick={() => {
                setSelected(new Set());
              }}
            >
              {t("Clear selection")}
            </Button>
          </div>
        ) : null}
        <div data-testid="members">
          <DataGrid
            table={table}
            recordCount={data.length}
            tableLayout={{ dense: true }}
            emptyMessage={
              <Empty>
                <EmptyHeader>
                  <EmptyTitle>{t("No members match")}</EmptyTitle>
                  <EmptyDescription>
                    {t("Try another name or role.")}
                  </EmptyDescription>
                </EmptyHeader>
                <EmptyContent>
                  <Button size="sm" variant="outline" onClick={clearFilters}>
                    {t("Clear filters")}
                  </Button>
                </EmptyContent>
              </Empty>
            }
          >
            <DataGridContainer>
              <DataGridScrollArea>
                <DataGridTable />
              </DataGridScrollArea>
            </DataGridContainer>
          </DataGrid>
        </div>
      </div>
    </MemberActionsContext>
  );
}
```

## Native (Expo)

The snippet uses `ActivityIndicator`, `Pressable`, `Text`, `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-organizations
```

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

```tsx
import { tenantOf, useAuth } from "better-supabase/react";
import { ActivityIndicator, Pressable, Text, View } from "react-native";

import { useMembers } from "../hooks/use-organizations";
import { API_SCHEMA } from "../lib/blocks";

/**
 * The active organization's members. Pressing a role switches it between member
 * and admin at once; the organizations module refuses a role above the
 * caller's, and the row shows the old role again.
 */
export function MembersTable() {
  const auth = useAuth();

  const { members, pending, error, setRole, remove } = useMembers({
    organizationId: tenantOf(auth),
    schema: API_SCHEMA,
  });

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

  return (
    <View style={{ gap: 4 }}>
      <Text style={{ fontSize: 17, fontWeight: "600" }}>Members</Text>
      {members.map((member) => {
        const busy = pending.includes(member.userId);

        const editable =
          member.userId !== auth.user?.id && member.role !== "owner";

        const next = member.role === "admin" ? "member" : "admin";

        return (
          <View
            key={member.userId}
            accessibilityState={{ busy }}
            style={{
              flexDirection: "row",
              alignItems: "center",
              gap: 8,
              paddingVertical: 8,
              opacity: busy ? 0.5 : 1,
            }}
          >
            <Text style={{ flex: 1 }} numberOfLines={1}>
              {member.userId === auth.user?.id ? "You" : member.userId}
            </Text>
            <Pressable
              accessibilityRole="button"
              accessibilityHint={editable ? `Changes the role to ${next}` : ""}
              disabled={!editable || busy}
              onPress={() =>
                void setRole({ userId: member.userId, role: next })
              }
            >
              <Text style={{ color: editable ? "#2563eb" : "#737373" }}>
                {member.role}
              </Text>
            </Pressable>
            {editable ? (
              <Pressable
                accessibilityRole="button"
                disabled={busy}
                onPress={() => void remove(member.userId)}
              >
                <Text style={{ color: "#b91c1c" }}>Remove</Text>
              </Pressable>
            ) : null}
          </View>
        );
      })}
      {error ? <Text style={{ color: "#b91c1c" }}>{error.message}</Text> : null}
    </View>
  );
}
```

## Prompt

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

### Web

```text
Build "Members table" in a React web app that uses shadcn/ui components. An organization's members with their roles, where a role change shows at once and a member can be removed.

It uses the better-supabase `organizations` block (Organizations). It calls the hook `useMembers` from `@/hooks/use-organizations`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add organizations` and apply the migration.
2. Add the shadcn components the recipe uses: `npx shadcn add avatar badge button empty input select`.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-organizations`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useMembers` from `@/hooks/use-organizations`, starting from the recipe's snippet (`apps/examples/nextjs/src/features/members/components/member-table.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/members-table.md
- Block docs: https://bettersupabase.com/docs/blocks/organizations
```

### Native

```text
Build "Members table" in a React Native app built with Expo. An organization's members with their roles, where a role change shows at once and a member can be removed.

It uses the better-supabase `organizations` block (Organizations). It calls the hook `useMembers` from `@/hooks/use-organizations`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add organizations` and apply the migration.
2. The recipe uses `ActivityIndicator`, `Pressable`, `Text`, `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-organizations`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useMembers` from `@/hooks/use-organizations`, starting from the recipe's snippet (`apps/examples/expo-powersync/src/components/members-table.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/members-table.md
- Block docs: https://bettersupabase.com/docs/blocks/organizations
```
