I would like to use Ant Design AutoComplete component to fetch data from API. The component has the following code:
const Example = ({ token, service }) => {
const [value, setValue] = useState('')
const [options, setOptions] = useState([])
const { data } = useFetch(value)
const onSelect = (data) => {
console.log('onSelect', data)
}
const onChange = (query) => {
console.log("Search query ", query);
setValue(query);
console.log("State value ", value);
if (value && value.length > 1) {
setOptions(
data ? data : []
)
} else {
setOptions([])
}
}
return (
<AutoComplete
value={value}
options={options}
onSelect={onSelect}
onChange={onChange}
/>
)
}
data for the options is provided by useFetch(value) hook. So the value should be updated as the user types in the input.
But the problem is that value in the state is always one character behind the actual search query. Here is the link to my codesandbox. You can see that console.log() for search query and state value are always different. Is there any way to fix that? I need state value to be always in synch with the search query.