I want to create a react-select drop-down where typing the input triggers an API call which asynchronously updates my options.
Here's what I have tried so far :
const [keyWord, setKeyWord] = useState('');
const [searchOpt, setSearchOpt] = useState([]);
const [selected, setSelected] = useState({});
async function handleSearchResult(query) {
await getStory({ keyWord: query }).then((data) => {
setSearchOpt(
data.hits.map((item) => {
return {
value: item.title,
label: item.title,
author: item.author,
created_at: item.created_at,
};
})
);
});
return searchOpt;
}
<AsyncSelect
classNamePrefix='select'
isSearchable={true}
isClearable={true}
cacheOptions
defaultOptions
loadOptions={handleSearchResult}
onChange={(option, { action }) => {
switch (action) {
case 'remove-value':
case 'clear':
setKeyWord(option ? option.value : '');
case 'select-option':
setSelected(option ? option : null);
default:
break;
}
}}
/>
The api calling works fine and on time with the input however the options are not being refreshed along with the output, it updates a step or two behind the input.