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;
2
Answers
Some time it can be face during the dangling the state updates and I’ll give some suggestions fix your issue,
1.Be careful handling the State update,
The state should be update asynchronously, and then component should re render after update the state, and careful while called the
setNamesList
and updatenameList
. and make sure theReactSearchAutocomplete
component properly listens to the changes ofnameList
, because when the component doesn’t catch the changes of state as expected then it will not re render.2.Check the doc and version of the
ReactSearchAutocomplete
.3.Check the component while updating the state changes , you can check it using console like that.
4.And you can use the useEffect for check the state changes
The issue is that the library you are using does not allow for dynamic data. This is one of their earliest issues. They will not be working towards it. The whole library was built keeping static requirements in mind.
You have the option to use some other library MUI autocomplete. They support server calls.
You can also make your own component, if the requirement is not that complex.
Basically what you are supposed to have is a:
Here is a demo
The above example should work for your use case. There is an inefficiency that API calls are not being cancelled. But that is not a direct requirement you have mentioned so I have not worked towards it.