AsyncSelect

Asynchronously load options for a select dropdown, perfect for searching large datasets or remote APIs.

AsyncSelect

The AsyncSelect component is a powerful dropdown that loads options asynchronously, ideal for searching large datasets or remote APIs. It supports multiple selection, option creation, and customizable loading behavior.

Basic AsyncSelect Example

import { AsyncSelect } from "@akitectio/aki-ui";

// Define a function that returns a Promise with options
const loadOptions = async (inputValue) => {
  // Simulate API call
  const response = await fetch(`/api/search?q=${inputValue}`);
  const data = await response.json();
  
  // Transform to the format expected by AsyncSelect
  return data.map(item => ({
    value: item.id,
    label: item.name
  }));
};

export default function SearchComponent() {
  return (
    <AsyncSelect
      loadOptions={loadOptions}
      placeholder="Search for an option"
      debounceMs={300}
      defaultOptions={true}
      cacheOptions={true}
    />
  );
}

Multiple Selection

Enable users to select multiple options by setting the multiple prop to true.

Multi-Select Example

import { useState } from "react";
import { AsyncSelect } from "@akitectio/aki-ui";

export default function MultiSelectExample() {
  const [selectedFruits, setSelectedFruits] = useState([]);

  return (
    <AsyncSelect
      loadOptions={loadFruits}
      placeholder="Select multiple fruits"
      multiple={true}
      value={selectedFruits}
      onChange={setSelectedFruits}
      closeMenuOnSelect={false}
    />
  );
}

Creatable Options

Allow users to create new options on the fly by setting the creatable prop to true.

Creatable AsyncSelect

import { AsyncSelect } from "@akitectio/aki-ui";

export default function CreatableSelectExample() {
  return (
    <AsyncSelect
      loadOptions={loadFruits}
      placeholder="Type to create a new fruit"
      creatable={true}
      createOptionMessage='Create "{inputValue}"'
    />
  );
}

API Integration Example

A practical example of integrating AsyncSelect with a real-world API.

Country Selector Example

Start typing a country name

import { useState } from "react";
import { AsyncSelect } from "@akitectio/aki-ui";

export default function CountrySelector() {
  const [selectedCountry, setSelectedCountry] = useState(null);

  // Load countries from an API
  const loadCountries = async (inputValue) => {
    try {
      const response = await fetch(
        `https://restcountries.com/v3.1/name/${inputValue}`
      );
      const data = await response.json();
      
      // Transform the API response to SelectOptions
      return data.map(country => ({
        value: country.cca2,
        label: country.name.common
      }));
    } catch (error) {
      console.error("Failed to load countries:", error);
      return [];
    }
  };

  return (
    <AsyncSelect
      loadOptions={loadCountries}
      placeholder="Search for a country"
      value={selectedCountry}
      onChange={setSelectedCountry}
      debounceMs={300}
      label="Country"
      helperText="Start typing a country name"
    />
  );
}

AsyncSelect Props

PropTypeDefaultDescription
loadOptions *(inputValue: string) => Promise<SelectOption[]>-Function that returns a promise with the options to display based on the input value
defaultOptionsboolean | SelectOption[]falseInitial options to display before the user types, or true to call loadOptions with empty string
debounceMsnumber300Milliseconds to wait before calling loadOptions after user input
cacheOptionsbooleanfalseWhether to cache previously loaded options
multiplebooleanfalseAllow multiple options to be selected
creatablebooleanfalseAllow creating new options not in the loaded options
createOptionMessagestring"Create "{inputValue}""Message template for creating new options. Use {inputValue} as placeholder
valuestring | string[] | null-The current value(s) of the select
onChange(value: string | string[] | null) => void-Callback fired when the value changes
variant"outline" | "filled" | "flushed" | "unstyled""outline"The visual style of the select
size"sm" | "md" | "lg""md"The size of the select
placeholderstring-Placeholder text when no option is selected
labelstring-Label text for the select
helperTextstring-Helper text displayed below the select
errorMessagestring-Error message to display when isInvalid is true
isInvalidbooleanfalseWhether the select is in an error state
disabledbooleanfalseWhether the select is disabled
clearablebooleantrueWhether the select value can be cleared
closeMenuOnSelectbooleantrue (single), false (multiple)Whether to close the menu when an option is selected
classNamestring-Additional CSS class for the select container