I'm trying to implement a search box with remote data using antd
's Select
and Option
. I'm expecting that when I enter text into the search box, a list of options will be rendered immediately. Instead, the options only appear after when I clear the search box.
I have these states:
const [symbol, setSymbol] = useState("");
const [searchResults, setSearchResults] = useState<React.ReactNode[]>();
and this component:
<Select
showSearch
value={symbol}
onSearch={handleSearch}
onChange={handleChange}
>
{searchResults}
</Select>
This is my handleSearch function:
const handleSearch = (value: string) => {
if (value) {
fetchStocksList(value, (data) => setSearchResults(data));
}
};
This is the function used to fetch data from an api, the console.log()
below can correctly log the data that I wanted:
const fetchStocksList = (
value: string,
callback: (data: React.ReactNode[]) => void
) => {
axios
.get(`${API_SERVER}/api/stocksinfo?search=${value}`)
.then((res) => {
let data: React.ReactNode[] = [];
res.data.forEach((row: any) => {
data.push(
<Option value={row.symbol}>{row.symbol + ": " + row.name}</Option>
);
});
return data;
})
.then((data) => {
console.log(data);
callback(data);
})
.catch((err) => console.error(err));
};
May I ask why does the options not appear until after I clear the text that I entered in the search box?
Turns out filterOption={false}
needs to be added to the Select
component, i.e. the following actually works:
<Select
showSearch
value={symbol}
onSearch={handleSearch}
onChange={handleChange}
filterOption={false}
>
{searchResults}
</Select>
The default value for filterOption
is set to true
.