I'm trying to make API calls to my backend and fetch suggestions as the user types into the input. Here's what I have:
const dispatch = useDispatch();
const [
fromOptions,
] = useSelector(({ search: { fromOptions } }) => [
fromOptions,
]);
const handleFromChange = useCallback(
async (event, value) => {
console.log('event', event);
console.log('value', value); // prints
if (!value || value?.length < 3) {
if (fromOptions.length) {
dispatch({
type: SET_FROM_OPTIONS_DELIVERY,
payload: [],
});
}
} else {
const query = {
params: {
query: value,
},
};
const { data } = await axios.get(api.GET.GET_OPTIONS, query);
dispatch({
type: SET_FROM_OPTIONS_DELIVERY,
payload: data,
});
}
},
[fromOptions],
);
<Autocomplete
options={fromOptions}
onInputChange={(event, value) => handleFromChange(event, value)}
onChange={() => console.log('selected!!')}
getOptionLabel={(option) => option}
style={{ width: window.innerWidth * 0.2 }}
renderInput={(params) => <TextField {...params} label='Combo box' variant='outlined' />}
/>
The const { data } = await axios.get(api.GET.GET_OPTIONS, query); part is reached when expected, correctly having had retrieved the data/suggestions, but when I set fromOptions in my dispatch action, it does not update the drop down. Performing an onBlur of the Autcomplete component followed by an onFocus seems to render the fetched suggestions, but I obviously can't expect the user to do this. How can I force a rerender on the fly?
CodeSandox
You could look at the console and see that the options array changes as the user types, but the drop down options change only on onBlur followed by an onFocus again.