# Organization switcher

> A menu of the user's organizations that switches the active one and refreshes the session for its tenant claim.

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

## Install the block

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

## Web (Next.js)

Add the shadcn components:

```bash
npx shadcn add dropdown-menu sidebar
```

Add the glue from the better-supabase registry:

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

From `apps/examples/nextjs/src/features/organization/components/organization-switcher-menu.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/nextjs/src/features/organization/components/organization-switcher-menu.tsx):

```tsx
"use client";

import { DbException } from "better-supabase";
import { useErrorMessage } from "better-supabase/react";
import { CheckIcon, ChevronsUpDownIcon, PlusIcon } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState, useTransition } from "react";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SidebarMenuButton } from "@/components/ui/sidebar";
import { useOrganizations } from "@/hooks/use-organizations";
import { organizationsConfig } from "@/lib/supabase/blocks/slices";
import { toast } from "@/lib/toast";

import type { OrganizationSummary } from "../organization-queries";

import { loadMyOrganizations } from "../organization-actions";
import { useRefreshSession } from "../use-refresh-session";
import { useRoleLabel } from "../use-role-label";
import { CreateOrganizationDialog } from "./create-organization-dialog";

function Mark({ name }: { name: string }) {
  return (
    <div
      aria-hidden="true"
      className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sm font-semibold text-sidebar-primary-foreground"
    >
      {name.slice(0, 1).toUpperCase()}
    </div>
  );
}

async function getOrganizations(): Promise<readonly OrganizationSummary[]> {
  const result = await loadMyOrganizations({});

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

  return result.data;
}

/**
 * The organization menu. The server renders it with its rows; switching goes
 * through `switch_organization`, refreshes the session for the new tenant
 * claim, then re-renders the server tree.
 */
export function OrganizationSwitcherMenu({
  initial,
  activeId: serverActiveId,
}: {
  initial: readonly OrganizationSummary[];
  activeId: string | null;
}) {
  const t = useExtracted("organization");
  const roleLabel = useRoleLabel();
  const errorMessage = useErrorMessage();
  const refreshSession = useRefreshSession();
  const [pending, startTransition] = useTransition();
  const [creating, setCreating] = useState(false);

  const { organizations, active, activeId, switchTo } = useOrganizations({
    load: getOrganizations,
    initial,
    activeId: serverActiveId,
    schema: organizationsConfig.api,
    onSwitched: () => refreshSession("/"),
  });

  const choose = (organization: OrganizationSummary) => {
    startTransition(async () => {
      const result = await switchTo(organization.id);

      if (!result.ok) {
        toast.error(errorMessage(result.error));

        return;
      }

      toast.success(t("Switched to {name}", { name: organization.name }));
    });
  };

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger
          disabled={pending}
          render={
            <SidebarMenuButton
              size="lg"
              className="data-popup-open:bg-sidebar-accent"
            />
          }
        >
          <Mark name={active?.name ?? "?"} />
          <div className="grid flex-1 text-left text-sm leading-tight">
            <span
              className="truncate font-medium"
              data-testid="organization-name"
            >
              {active?.name ?? t("No organization")}
            </span>
            <span className="truncate text-xs text-muted-foreground capitalize">
              {active ? active.plan : t("Create one to start")}
            </span>
          </div>
          <span className="sr-only">{t("Switch organization")}</span>
          <ChevronsUpDownIcon className="ml-auto" />
        </DropdownMenuTrigger>
        <DropdownMenuContent className="w-64" align="start" side="bottom">
          <DropdownMenuGroup>
            <DropdownMenuLabel>{t("Organizations")}</DropdownMenuLabel>
            {(organizations ?? initial).map((organization) => (
              <DropdownMenuItem
                key={organization.id}
                className="gap-2"
                onClick={() => {
                  if (organization.id !== activeId) {
                    choose(organization);
                  }
                }}
              >
                <Mark name={organization.name} />
                <div className="grid flex-1 leading-tight">
                  <span className="truncate">{organization.name}</span>
                  <span className="text-xs text-muted-foreground">
                    {roleLabel(organization.role)}
                  </span>
                </div>
                {organization.id === activeId ? <CheckIcon /> : null}
              </DropdownMenuItem>
            ))}
          </DropdownMenuGroup>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            onClick={() => {
              setCreating(true);
            }}
          >
            <PlusIcon />
            {t("Create organization")}
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      <CreateOrganizationDialog open={creating} onOpenChange={setCreating} />
    </>
  );
}
```

## 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/organization-switcher.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/expo-powersync/src/components/organization-switcher.tsx):

```tsx
import type { OrganizationMembership } from "better-supabase/blocks/organizations";

import { ActivityIndicator, Pressable, Text, View } from "react-native";

import type { UseOrganizationsOptions } from "../hooks/use-organizations";

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

/**
 * The caller's organizations. Pressing one switches to it, refreshes the
 * session so the token carries the new tenant, and loads the list again. `load`
 * reads them elsewhere, such as from the PowerSync database, and `onSwitched`
 * replaces the refresh, such as one that also reconnects sync.
 */
export function OrganizationSwitcher(
  props: Pick<
    UseOrganizationsOptions<OrganizationMembership>,
    "load" | "onSwitched"
  >,
) {
  const { organizations, activeId, switching, error, switchTo } =
    useOrganizations({ ...props, schema: API_SCHEMA });

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

  return (
    <View style={{ gap: 4 }}>
      <Text style={{ fontSize: 17, fontWeight: "600" }}>Organizations</Text>
      {organizations.map((organization) => (
        <Pressable
          key={organization.id}
          accessibilityRole="button"
          accessibilityState={{
            selected: organization.id === activeId,
            busy: organization.id === switching,
          }}
          disabled={switching !== undefined || organization.id === activeId}
          onPress={() => void switchTo(organization.id)}
          style={{ flexDirection: "row", gap: 8, paddingVertical: 8 }}
        >
          <Text style={{ width: 16 }}>
            {organization.id === activeId ? "✓" : ""}
          </Text>
          <Text style={{ flex: 1 }}>{organization.name}</Text>
          <Text style={{ color: "#737373" }}>{organization.role}</Text>
        </Pressable>
      ))}
      {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 "Organization switcher" in a React web app that uses shadcn/ui components. A menu of the user's organizations that switches the active one and refreshes the session for its tenant claim.

It uses the better-supabase `organizations` block (Organizations). It calls the hook `useOrganizations` 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 dropdown-menu sidebar`.
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 `useOrganizations` from `@/hooks/use-organizations`, starting from the recipe's snippet (`apps/examples/nextjs/src/features/organization/components/organization-switcher-menu.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/org-switcher.md
- Block docs: https://bettersupabase.com/docs/blocks/organizations
```

### Native

```text
Build "Organization switcher" in a React Native app built with Expo. A menu of the user's organizations that switches the active one and refreshes the session for its tenant claim.

It uses the better-supabase `organizations` block (Organizations). It calls the hook `useOrganizations` 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 `useOrganizations` from `@/hooks/use-organizations`, starting from the recipe's snippet (`apps/examples/expo-powersync/src/components/organization-switcher.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/org-switcher.md
- Block docs: https://bettersupabase.com/docs/blocks/organizations
```
