# useCopyToClipboard

Copies text to the clipboard and tracks whether it worked.

Source: [use-copy-to-clipboard.ts](https://github.com/jakejarvis/jarvis-ui/blob/main/src/hooks/use-copy-to-clipboard.ts)

```tsx
"use client";

import { Button } from "@/components/ui/button";
import { CheckIcon, CopyIcon, XIcon } from "@/components/ui/icons";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";

export default function UseCopyToClipboardBasic() {
  const { copy, status } = useCopyToClipboard();

  return (
    <Button variant="secondary" onClick={() => copy("https://example.com/invite/7f3a9c")}>
      {status === "copied" ? <CheckIcon /> : status === "failed" ? <XIcon /> : <CopyIcon />}
      {status === "copied" ? "Copied" : status === "failed" ? "Couldn’t copy" : "Copy invite link"}
    </Button>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the hook:

```bash
npx shadcn@latest add @jarvis/use-copy-to-clipboard
```

## Usage

```tsx
"use client";

import { Button } from "@/components/ui/button";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";

export function CopyInviteLink({ url }: { url: string }) {
  const { copy, status } = useCopyToClipboard();

  return (
    <Button variant="secondary" onClick={() => copy(url)}>
      {status === "copied" ? "Copied" : "Copy invite link"}
    </Button>
  );
}
```

`copy` writes the text to the clipboard and resolves to whether it succeeded. After a copy,
`status` is `copied` or `failed` for two seconds, or for `resetAfter` milliseconds, so a control can
show the result. Otherwise it's `idle`. `reset` sets it back to `idle` early. This is the hook
behind [Copy Button](https://ui.jarv.is/components/copy-button.md), and other components with a copy button use it too.

When the Clipboard API is unavailable or rejects the write, as it can over plain HTTP or in some
embedded browsers, the hook falls back to copying from a hidden text area. It then restores the
previous selection and focus.

## Examples

### Text that loads first

When the text isn't ready yet, pass `copy` a promise of it, such as from a fetch. Safari only lets
a page write to the clipboard during the click that requested it, so the hook passes the promise to
the clipboard immediately. The clipboard receives the text once the promise resolves.

```tsx
"use client";

import { CheckIcon, KeyRoundIcon, XIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";

async function createToken() {
  await new Promise((resolve) => setTimeout(resolve, 800));
  return `tok_${crypto.randomUUID().replaceAll("-", "")}`;
}

export default function UseCopyToClipboardPromise() {
  const { copy, status } = useCopyToClipboard();

  return (
    <Button variant="secondary" onClick={() => copy(createToken())}>
      {status === "copied" ? <CheckIcon /> : status === "failed" ? <XIcon /> : <KeyRoundIcon />}
      {status === "copied"
        ? "Token copied"
        : status === "failed"
          ? "Couldn’t copy"
          : "Create and copy a token"}
    </Button>
  );
}
```

## API

### useCopyToClipboard

`useCopyToClipboard(options?)` takes these options.

| Option        | Type                         | Default | Description                                                                                         |
| ------------- | ---------------------------- | ------- | --------------------------------------------------------------------------------------------------- |
| `resetAfter?` | `number`                     | `2000`  | How long the copied or failed status lasts before it resets to `idle`, in milliseconds.             |
| `onCopy?`     | `((value: string) => void)`  | —       | Called with the text once it's written to the clipboard.                                            |
| `onError?`    | `((error: unknown) => void)` | —       | Called with the error when the text can't be written to the clipboard, or when its promise rejects. |

It returns:

| Value    | Type                                                    | Description                                                                                                                                                                           |
| -------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `copy`   | `(text: string \| Promise<string>) => Promise<boolean>` | Writes the text to the clipboard. Pass a promise when the text has to load first. The copy still counts as part of the click that started it. Resolves to whether the copy succeeded. |
| `reset`  | `() => void`                                            | Resets `status` to `idle` immediately and ignores any copy still in progress.                                                                                                         |
| `status` | `"copied" \| "failed" \| "idle"`                        | `copied` or `failed` for `resetAfter` after a copy, and `idle` otherwise.                                                                                                             |

The file also exports `CopyStatus`, the type of `status`.
