Mohammad I
Mohammad I

Reputation: 90

React Bootstrap AsyncTypeahead onlick

I am not able to implement onClick functionality on AsyncTypeahead to console log the user ID after I find the user. can someone please help. thanks

const SEARCH_URI = 'https://api.github.com/search/users';
const AsyncExample = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [options, setOptions] = useState([]);
  const handleSearch = (query) => {
    setIsLoading(true);
    fetch(`${SEARCH_URI}?q=${query}+in:login&page=1&per_page=50`)
      .then((resp) => resp.json())
      .then(({ items }) => {
        const options = items.map((i) => ({
          avatar_url: i.avatar_url,
          id: i.id,
          login: i.login,
        }));

        setOptions(options);
        setIsLoading(false);
      });
  };

  const filterBy = () => true;

  return (
    <AsyncTypeahead
      filterBy={filterBy}
      id="async-example"
      isLoading={isLoading}
      labelKey="login"
      minLength={2}
      onSearch={handleSearch}
      options={options}
      placeholder="Search for a Github user..."
    />
  );
};

Upvotes: 0

Views: 696

Answers (1)

ericgio
ericgio

Reputation: 3509

Try using onChange, which fires after a menu option has been selected:

<AsyncTypeahead
  ...
  onChange={(selected) => {
    console.log(selected[0]?.id);
  }}
/>

Note that selected is always an array.

Upvotes: 1

Related Questions