ant design onSelect is not firing

1.5k Views Asked by At

I'm trying to use Autocomplete from Ant Design, but the "onSelect" is not firing. Everything else is working well - when I type into the search bar, my ingredient list appears and filters as intended. If I console log "data" in onChange, the search's values appears (the "data"). When I click on an item from my filtered pop up menu, the menu disappears, the value in the input remains the same as before (i.e. it does not change to the selected item) and nothing is fired to the console. What am I doing wrong?

UPDATE: Added a sandbox.

Thanks in advance for your help.

export default function Searchbar() {
  const [value, setValue] = useState('')
  const [options, setOptions] = useState<{ value: string }[]>([]);

  const ingredients = useSelector(state => state.ingredients);

  const onSearch = (searchTerm: string) => {
    setOptions(
      !searchTerm ? [] : ingredients.filter(ferment =>
        ferment.label.toLowerCase().includes(searchTerm.toLocaleLowerCase())
      ))
    };

    const onSelect = (data: string) => {
      console.log("onSelect", data);

    };

    const onChange = (data: string) => {
      setValue(data);
      console.log(data)
    };
     
    return (
      <>

    <AutoComplete
        options={options}
        value={value}
        style={{ width: 200 }}
        onSelect={onSelect}
        onSearch={onSearch}
        onChange={onChange}
        placeholder="looking for"
      />
       
        </>
    )
}
2

There are 2 best solutions below

0
Yuri Dzabaev On

<AutoComplete /> expects prop options with items that must have value prop.

You pass ingredients as options to AutoComplete and ingredients don't have this property.

This is the reason why the callback onSelect is not firing.

0
Shahed On

When creating search options we need to specify value key :pair for example value: item?.title,for onSelect to understand which one was selected.