# 异步选项

加载搜索结果，取消过期的请求，并获取下一页。

`useAsyncOptions` 在用户输入时加载条目。它会等输入停下来，取消被取代的请求，并在加载期间保留之前的结果。

```tsx title="async.tsx"
import { useAsyncOptions } from "@ui-sdk/solid/async-options"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxStatus,
  ComboboxTrigger,
} from "@ui-sdk/solid/combobox"
import { For } from "solid-js"

const movieTitles = [
  "The Shawshank Redemption",
  "The Godfather",
  "The Dark Knight",
  "Pulp Fiction",
  "Schindler's List",
  "The Lord of the Rings",
  "Fight Club",
  "Forrest Gump",
  "Inception",
  "The Matrix",
  "Goodfellas",
  "Interstellar",
  "Parasite",
  "Spirited Away",
  "Whiplash",
  "The Prestige",
  "The Departed",
  "Gladiator",
  "Alien",
  "Casablanca",
  "Amélie",
  "Arrival",
]

function searchMovies(query: string, { signal }: { signal: AbortSignal }) {
  return new Promise<{ value: string; label: string }[]>((resolve, reject) => {
    const timer = setTimeout(() => {
      const needle = query.trim().toLowerCase()
      resolve(
        movieTitles
          .filter((title) => title.toLowerCase().includes(needle))
          .map((title) => ({
            value: title.toLowerCase().replace(/\W+/g, "-"),
            label: title,
          }))
      )
    }, 500)
    signal.addEventListener("abort", () => {
      clearTimeout(timer)
      reject(signal.reason)
    })
  })
}

function Example() {
  const movies = useAsyncOptions(searchMovies, {
    debounce: 300,
    query: "the",
    immediate: true,
  })

  return (
    <Combobox
      items={movies.items}
      defaultQuery="the"
      filter={false}
      status={movies.status}
      onQueryChange={(query) => movies.setQuery(query)}
    >
      <div data-slot="stack">
        <ComboboxLabel>Movie</ComboboxLabel>
        <div data-slot="row">
          <ComboboxInput placeholder="Search movies…" />
          <ComboboxTrigger aria-label="Show movies">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </ComboboxTrigger>
        </div>
      </div>
      <ComboboxContent>
        <ComboboxStatus>
          {(state) =>
            state.status === "error"
              ? "Couldn't load movies."
              : state.loading
                ? "Searching…"
                : `${state.count} ${state.count === 1 ? "movie" : "movies"}`
          }
        </ComboboxStatus>
        <ComboboxEmpty>
          {(state) =>
            state.empty && !state.loading
              ? `No movies match “${state.query}”.`
              : null
          }
        </ComboboxEmpty>
        <ComboboxList>
          {(state) => (
            <For
              each={
                state.items as {
                  value: string
                  label: string
                  disabled?: boolean
                }[]
              }
            >
              {(item) => (
                <ComboboxItem
                  value={item.value}
                  label={item.label}
                  disabled={item.disabled}
                >
                  {item.label}
                  <ComboboxItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </ComboboxItemIndicator>
                </ComboboxItem>
              )}
            </For>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  )
}

export { Example }
```

更改电影搜索，等待结果。用方向键选择一部电影，然后按 Enter。

## 加载结果
把加载函数传给这个辅助函数。这个示例期望 `/api/movies` 返回一个电影标题数组：

```tsx
import { useAsyncOptions } from "@ui-sdk/solid/async-options"
import {
  Combobox,
  ComboboxContent,
  ComboboxInput,
} from "@ui-sdk/solid/combobox"

function Example() {
  const movies = useAsyncOptions<string>(async (query, { signal }) => {
    const response = await fetch(`/api/movies?q=${encodeURIComponent(query)}`, {
      signal,
    })
    if (!response.ok) throw new Error("Couldn't load movies")
    return response.json()
  })

  return (
    <Combobox
      items={movies.items}
      filter={false}
      status={movies.status}
      onQueryChange={movies.setQuery}
    >
      <ComboboxInput aria-label="Movie" placeholder="Search movies…" />
      <ComboboxContent />
    </Combobox>
  )
}

export { Example }
```

`movies` 上的字段是响应式 getter。在 JSX 里读取它们，组件才能跟随每一次加载。

把 `signal` 传给 `fetch`，这样更新的搜索可以取消这个请求。组件卸载时，这个辅助函数也会取消。把 `filter` 设为 false，就把匹配和排序交给服务器。

用 `ComboboxStatus` 和 `ComboboxEmpty` 显示加载中、错误和空结果的消息，就像演示里那样。同样的模式也适用于 [Select](https://ui-sdk.cn/docs/solid/components/select#async-search)、[Autocomplete](https://ui-sdk.cn/docs/solid/components/autocomplete#async-suggestions) 和 [Command](https://ui-sdk.cn/docs/solid/components/command#async-results)。

## 选择何时加载
第二个参数设置起始行为：

| 选项        | 作用                                                 | 默认值  |
| ----------- | ---------------------------------------------------- | ------- |
| `debounce`  | 请求开始前，输入必须暂停的毫秒数。                   | `200`   |
| `query`     | 起始的搜索文本。                                     | `""`    |
| `immediate` | 组件一挂载就加载这段文本。                           | `false` |
| `minLength` | 文本在开始加载前所需的字符数。更短的文本会清空条目。 | `0`     |

要获取初始选项，就在加载函数后面加上 `{ immediate: true, debounce: 300 }`。在第一次加载开始之前，`status` 就已经是 `"loading"`，所以列表不会闪一下空状态。如果你设置了 `query`，就让组件的 `defaultQuery` 使用同样的起始文本。

## 加载更多
对于分页的结果，加载函数会收到从 `0` 开始的 `page`。返回 `{ items, hasMore }`：

```ts
import type { AsyncOptionsContext } from "@ui-sdk/solid/async-options"

async function loadMoviePages(
  query: string,
  { signal, page }: AsyncOptionsContext
) {
  const response = await fetch(
    `/api/movies?q=${encodeURIComponent(query)}&page=${page}`,
    { signal }
  )
  if (!response.ok) throw new Error("Couldn't load movies")
  const data: { titles: string[]; next: number | null } = await response.json()
  return { items: data.titles, hasMore: data.next !== null }
}

export { loadMoviePages }
```

把 `loadMoviePages` 传给 `useAsyncOptions`，替换上面内联的加载函数。

在 Combobox 上绑定 `onLoadMore={movies.loadMore}`。当滚动或键盘导航到达最后一个条目时，它会请求另一页。这个辅助函数会把新条目追加到后面。

```tsx title="infinite.tsx"
import { useAsyncOptions } from "@ui-sdk/solid/async-options"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxStatus,
  ComboboxTrigger,
} from "@ui-sdk/solid/combobox"
import { For } from "solid-js"

const movieTitles = [
  "The Shawshank Redemption",
  "The Godfather",
  "The Dark Knight",
  "Pulp Fiction",
  "Schindler's List",
  "The Lord of the Rings",
  "Fight Club",
  "Forrest Gump",
  "Inception",
  "The Matrix",
  "Goodfellas",
  "Interstellar",
  "Parasite",
  "Spirited Away",
  "Whiplash",
  "The Prestige",
  "The Departed",
  "Gladiator",
  "Alien",
  "Casablanca",
  "Amélie",
  "Arrival",
]

function searchMoviePages(
  query: string,
  { signal, page }: { signal: AbortSignal; page: number }
) {
  return new Promise<{
    items: { value: string; label: string }[]
    hasMore: boolean
  }>((resolve, reject) => {
    const timer = setTimeout(() => {
      const needle = query.trim().toLowerCase()
      const found = movieTitles
        .filter((title) => title.toLowerCase().includes(needle))
        .map((title) => ({
          value: title.toLowerCase().replace(/\W+/g, "-"),
          label: title,
        }))
      resolve({
        items: found.slice(page * 5, page * 5 + 5),
        hasMore: found.length > page * 5 + 5,
      })
    }, 500)
    signal.addEventListener("abort", () => {
      clearTimeout(timer)
      reject(signal.reason)
    })
  })
}

function Example() {
  const movies = useAsyncOptions(searchMoviePages, { immediate: true })

  return (
    <Combobox
      items={movies.items}
      filter={false}
      status={movies.status}
      onQueryChange={(query) => movies.setQuery(query)}
      onLoadMore={movies.loadMore}
    >
      <div data-slot="stack">
        <ComboboxLabel>Movie</ComboboxLabel>
        <div data-slot="row">
          <ComboboxInput placeholder="Search movies…" />
          <ComboboxTrigger aria-label="Show movies">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </ComboboxTrigger>
        </div>
      </div>
      <ComboboxContent>
        <ComboboxEmpty>
          {(state) =>
            state.empty && !state.loading ? "No movies found." : null
          }
        </ComboboxEmpty>
        <ComboboxList>
          {(state) => (
            <For
              each={
                state.items as {
                  value: string
                  label: string
                  disabled?: boolean
                }[]
              }
            >
              {(item) => (
                <ComboboxItem
                  value={item.value}
                  label={item.label}
                  disabled={item.disabled}
                >
                  {item.label}
                  <ComboboxItemIndicator>
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M20 6 9 17l-5-5" />
                    </svg>
                  </ComboboxItemIndicator>
                </ComboboxItem>
              )}
            </For>
          )}
        </ComboboxList>
        <ComboboxStatus>
          {(state) =>
            state.loading
              ? "Loading more…"
              : movies.hasMore
                ? `${state.count} loaded`
                : `All ${state.count}`
          }
        </ComboboxStatus>
      </ComboboxContent>
    </Combobox>
  )
}

export { Example }
```

打开电影列表并向下滚动，或用 Arrow Down 到达最后一个结果。下一页会加到列表里。

## 重试搜索
请求进行中时，`status` 是 `"loading"`；失败之后是 `"error"`；其他时候是 `"idle"`。`error` 保存失败信息，之前的结果仍然可用。

在重试按钮里调用 `movies.reload()`，从第 `0` 页开始重新加载当前的查询。`movies.hasMore` 告诉你是否还有另一页可用。
