# useAsyncOptions

Loads options for typed text after a pause, and reports why one is highlighted.

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

```tsx
"use client";

import * as React from "react";

import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { searchLibraries } from "@/examples/data";
import { useAsyncOptions } from "@/hooks/use-async-options";

export default function UseAsyncOptionsSearch() {
  const [query, setQuery] = React.useState("");
  const { items, loading, error } = useAsyncOptions(query, { load: searchLibraries });

  return (
    <div className="flex w-full max-w-xs flex-col gap-3">
      <Input
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        placeholder="Search libraries"
        aria-label="Search libraries"
        aria-controls="library-results"
      />
      <div id="library-results" aria-live="polite" className="min-h-28">
        {loading ? (
          <p className="flex items-center gap-2 text-muted-foreground">
            <Spinner /> Searching…
          </p>
        ) : error ? (
          <p className="text-destructive">Couldn’t search. Try again.</p>
        ) : query.trim() === "" ? (
          <p className="text-muted-foreground">Type to search, such as “re”.</p>
        ) : items.length === 0 ? (
          <p className="text-muted-foreground">No libraries match “{query.trim()}”.</p>
        ) : (
          <ul className="flex flex-col gap-1">
            {items.map((library) => (
              <li key={library}>{library}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
```

## 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-async-options
```

## Usage

```tsx
"use client";

import * as React from "react";

import { Input } from "@/components/ui/input";
import { useAsyncOptions } from "@/hooks/use-async-options";

async function searchUsers(query: string, { signal }: { signal: AbortSignal }) {
  const response = await fetch(`/api/users?q=${encodeURIComponent(query)}`, { signal });
  return (await response.json()) as string[];
}

export function UserSearch() {
  const [query, setQuery] = React.useState("");
  const { items, loading, error } = useAsyncOptions(query, { load: searchUsers });

  return (
    <>
      <Input value={query} onChange={(event) => setQuery(event.target.value)} />
      {loading ? <p>Searching…</p> : error ? <p>Couldn’t search.</p> : null}
      <ul>
        {items.map((user) => (
          <li key={user}>{user}</li>
        ))}
      </ul>
    </>
  );
}
```

`load` runs once the query has stayed the same for `delay` milliseconds. It receives the trimmed
query and a signal that aborts when users type again, so a slow response never replaces a newer
one. An empty query loads nothing.

While new options load, `items` keeps the last ones so the list doesn't flash empty. `loading`
and `error` report the state of the latest load. `deps` lists what `load` reads besides the query,
such as a selected category, and options load again when any of them changes.

This is the hook behind `loadItems` in [Autocomplete](https://ui.jarv.is/components/autocomplete.md) and
`loadSuggestions` in [Tag Input](https://ui.jarv.is/components/tag-input.md).

## Examples

### Reloading when a filter changes

`load` reads the selected category here, so the category goes in `deps`. Switching it loads the
options for the same query again, from the other source.

```tsx
"use client";

import * as React from "react";

import { Input } from "@/components/ui/input";
import { SegmentedControl, SegmentedControlItem } from "@/components/ui/segmented-control";
import { Spinner } from "@/components/ui/spinner";
import { searchLibraries, searchPeople } from "@/examples/data";
import { useAsyncOptions } from "@/hooks/use-async-options";

type Category = "libraries" | "people";

export default function UseAsyncOptionsCategory() {
  const [category, setCategory] = React.useState<Category>("libraries");
  const [query, setQuery] = React.useState("");
  const { items, loading } = useAsyncOptions(query, {
    load: async (text, options) =>
      category === "libraries"
        ? searchLibraries(text, options)
        : (await searchPeople(text, options)).map((person) => person.name),
    deps: [category],
  });

  return (
    <div className="flex w-full max-w-xs flex-col gap-3">
      <SegmentedControl
        value={category}
        onValueChange={(value) => {
          if (value === "libraries" || value === "people") setCategory(value);
        }}
        aria-label="Search in"
      >
        <SegmentedControlItem value="libraries">Libraries</SegmentedControlItem>
        <SegmentedControlItem value="people">People</SegmentedControlItem>
      </SegmentedControl>
      <Input
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        placeholder={category === "libraries" ? "Search libraries" : "Search people"}
        aria-label="Search"
        aria-controls="category-results"
      />
      <div id="category-results" aria-live="polite" className="min-h-28">
        {loading ? (
          <p className="flex items-center gap-2 text-muted-foreground">
            <Spinner /> Searching…
          </p>
        ) : query.trim() === "" ? (
          <p className="text-muted-foreground">Type to search, such as “a”.</p>
        ) : items.length === 0 ? (
          <p className="text-muted-foreground">Nothing matches “{query.trim()}”.</p>
        ) : (
          <ul className="flex flex-col gap-1">
            {items.map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
```

### In an Autocomplete or Combobox

When you build on Base UI's Autocomplete or Combobox, pass `onItemHighlighted` to the root's prop
of the same name. `getHighlight()` then reports why the highlighted option is highlighted:
users chose it with the keyboard or pointer (`chosen`), it was highlighted automatically (`auto`),
or it was highlighted automatically among results that are being replaced (`stale`). Pressing Enter
on a `stale` option should submit the typed text rather than pick the option.

`getSeen()` returns every option loaded so far for the current `deps`, such as to accept one
that users typed out in full. When you pass `itemToStringValue`, it returns one option for
each text.

This example builds on [Combobox](https://ui.jarv.is/components/combobox.md) to pick an assignee. It passes
`filter={null}`, since the endpoint already filters. A combobox has no typed text to submit, so
Enter does nothing while the highlighted option is `stale`.

```tsx
"use client";

import * as React from "react";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxList,
  ComboboxStatus,
} from "@/components/ui/combobox";
import { Spinner } from "@/components/ui/spinner";
import { searchPeople, type Person } from "@/examples/data";
import { useAsyncOptions } from "@/hooks/use-async-options";

export default function UseAsyncOptionsCombobox() {
  const [query, setQuery] = React.useState("");
  const { items, loading, error, onItemHighlighted, getHighlight } = useAsyncOptions(query, {
    load: searchPeople,
  });

  return (
    <Combobox
      items={items}
      filter={null}
      autoHighlight
      inputValue={query}
      onInputValueChange={setQuery}
      itemToStringLabel={(person: Person) => person.name}
      isItemEqualToValue={(person: Person, value: Person) => person.value === value.value}
      onItemHighlighted={onItemHighlighted}
    >
      <ComboboxInput
        placeholder="Search people"
        aria-label="Assignee"
        className="w-full max-w-xs"
        onKeyDown={(event) => {
          if (event.key === "Enter" && getHighlight() === "stale") {
            event.preventBaseUIHandler();
          }
        }}
      />
      <ComboboxContent>
        <ComboboxStatus>
          {loading ? (
            <>
              <Spinner /> Searching…
            </>
          ) : error ? (
            "Couldn’t search. Try again."
          ) : null}
        </ComboboxStatus>
        <ComboboxEmpty>
          {loading || error ? null : query.trim() === "" ? "Type a name." : "No one matches."}
        </ComboboxEmpty>
        <ComboboxList>
          {(person: Person) => (
            <ComboboxItem key={person.value} value={person}>
              <Avatar size="sm">
                <AvatarImage src={person.image} alt="" />
                <AvatarFallback>{person.initials}</AvatarFallback>
              </Avatar>
              {person.name}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  );
}
```

## API

### useAsyncOptions

`useAsyncOptions(query, options?)` takes the typed text and these options.

| Option               | Type                                        | Default | Description                                                                                                                                                    |
| -------------------- | ------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `load?`              | `LoadOptions<Item>`                         | —       | Loads the options for a query, such as from a search endpoint. It receives a signal that aborts once the query changes. Without it, nothing loads.             |
| `deps?`              | `React.DependencyList`                      | `[]`    | The values `load` reads besides the query, such as a selected category. Options load again when any of them changes, compared as an effect's dependencies are. |
| `delay?`             | `number`                                    | `300`   | How long the query has to stay the same before loading, in milliseconds.                                                                                       |
| `itemToStringValue?` | `((item: Item) => string)`                  | —       | Returns an option's text, which `getSeen` uses to tell options apart. Without it, they're compared by value.                                                   |
| `onLoad?`            | `((query: string, items: Item[]) => void)`  | —       | Called when options for a query arrive.                                                                                                                        |
| `onError?`           | `((query: string, error: unknown) => void)` | —       | Called when loading options for a query fails.                                                                                                                 |

It returns:

| Value               | Type                                                    | Description                                                                                                               |
| ------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `items`             | `Item[]`                                                | The options loaded for the query, or the last ones while new ones load. Empty while the query is empty or without `load`. |
| `loading`           | `boolean`                                               | Whether options for the query are loading, including during the `delay`.                                                  |
| `error`             | `boolean`                                               | Whether loading options for the query failed. `onError` receives the error.                                               |
| `getSeen`           | `() => Item[]`                                          | Returns every option loaded so far for the current `deps`, deduplicated by `itemToStringValue`.                           |
| `onItemHighlighted` | `(item: unknown, details: { reason: string; }) => void` | Pass to the Autocomplete or Combobox root's `onItemHighlighted`, so `getHighlight` can tell why one is highlighted.       |
| `getHighlight`      | `() => OptionHighlight`                                 | Returns why the highlighted option is highlighted, to decide whether Enter should pick it.                                |

The file also exports `LoadOptions<Item>`, the type of `load`, and `OptionHighlight`, the
type `getHighlight` returns.
