I’m using ReactSearchAutocomplete to display a list of 10 suggested names from a mySql query. The query is performed with a 100ms delay on user input, and it works fine but I’m clearly not handling the state properly because the query will return results fine, but upon calling setState, the search bar does not provide suggestions as would be expected.
Only if I then continue typing and trigger another query do the search results show up, and they seemingly are the results of the previous query.
My question is, how do I get the autocomplete component to properly render the suggested results from my query only AFTER setting the state of the namesList?
const SearchBar = () => {
const [namesList, setNamesList] = useState([]);
const handleOnSearch = (searchTerm) => {
if (searchTerm.length < 2) {
return;
}
let queryString = "url/api/search/" + searchTerm;
if (isDev) {
queryString = "http://localhost:3001/search/" + searchTerm;
}
fetch(queryString)
.then((response) => response.json())
.then((json) => {
let searchResults = json.map((o) => ({ id: o.name, name: o.name }));
setNamesList(searchResults);
})
.catch((error) => console.error(error));
};
return (
<div className="search-bar">
<ReactSearchAutocomplete
items={namesList}
onSearch={handleOnSearch}
autoFocus={true}
inputDebounce={100}
showNoResults={false}
/>
</div>
);
};
export default SearchBar;