# useAsyncSuggestions

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

Source: [use-async-suggestions.ts](https://github.com/jakejarvis/jarvis-ui/blob/main/src/hooks/use-async-suggestions.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 { useAsyncSuggestions } from "@/hooks/use-async-suggestions";

export default function UseAsyncSuggestionsSearch() {
  const [query, setQuery] = React.useState("");
  const { items, loading, error } = useAsyncSuggestions(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 text-sm">
        {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-suggestions
```

## Usage

```tsx
"use client";

import * as React from "react";

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

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 } = useAsyncSuggestions(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 suggestions 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 suggestions 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).

### 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 suggestion 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` suggestion should submit the typed text rather than pick the suggestion.

`getSeen()` returns every suggestion 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 suggestion for
each text.

## API

### useAsyncSuggestions

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

| Option               | Type                                        | Default | Description                                                                                                                                                        |
| -------------------- | ------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `load?`              | `LoadSuggestions<Item>`                     | —       | Loads the suggestions 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. Suggestions 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 a suggestion's text, which `getSeen` uses to tell suggestions apart. Without it, they're compared by value.                                                |
| `onLoad?`            | `((query: string, items: Item[]) => void)`  | —       | Called when suggestions for a query arrive.                                                                                                                        |
| `onError?`           | `((query: string, error: unknown) => void)` | —       | Called when loading suggestions for a query fails.                                                                                                                 |

It returns:

| Value               | Type                                                    | Description                                                                                                                   |
| ------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `items`             | `Item[]`                                                | The suggestions loaded for the query, or the last ones while new ones load. Empty while the query is empty or without `load`. |
| `loading`           | `boolean`                                               | Whether suggestions for the query are loading, including during the `delay`.                                                  |
| `error`             | `boolean`                                               | Whether loading suggestions for the query failed. `onError` receives the error.                                               |
| `getSeen`           | `() => Item[]`                                          | Returns every suggestion 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`      | `() => SuggestionHighlight`                             | Returns why the highlighted suggestion is highlighted, to decide whether Enter should pick it.                                |

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