I've been implementing a search as you type feature and would like to have the function search which handles my API calls to be debounced. Which works fine if I only call the debounced_search function within the event handler, but I also need to update the input value, which should happen immediately.
My issue is now that as soon as I add setInput(newInputValue); to the event handler, the search function is no longer debounced but gets called immediately on every change though I'm using the debounced version.
Why does that happen? And how do I solve this?
Thank you.
import React from 'react'
import Autocomplete from '@mui/material/Autocomplete';
import { selectClasses, TextField } from '@mui/material';
import debounce from 'lodash/debounce';
function Searchbar() {
const [options, setOptions] = React.useState([]);
const [input, setInput] = React.useState("");
const search = (event, newInputValue) => {
console.log("Debounced Called")
}
const debounced_search = debounce(search, 500)
return (<Autocomplete
id="free-solo"
freeSolo
renderInput={(params) => <TextField {...params} label="Test" />}
inputValue={input}
options={options}
onInputChange={function (event, newInputValue) {
debounced_search(event, newInputValue);
setInput(newInputValue);
console.log("Input Changed")
}}
/>)
}
export default Searchbar