I am building a basic weather forecast app using React and Material UI. I am using Autocomplete provided by MUI.
The issue I am facing is that after I type a place-name in the text field and get the options rendered, the text field loses its focus. I understand it is due to the setPlaceList(response.data);
cause when I comment it out and put only console.log(response.data);
the text field doesn't lose its focus.
Here is the code:
const [placeList, setPlaceList] = useState([]);
const onValueChange = (e) => {
if(e.target.value.length > 3){
getCordinates(e.target.value);
}
}
const getCordinates = debounce (place => {
axios.get(`https://api.locationiq.com/v1/autocomplete.php?key=${api_key}&q=${place}`)
.then((response) => {
setPlaceList(response.data);
console.log(response.data)
})
.catch((e)=>{
window.alert("ENTER CORRECT LOCATION")
})
},500);
<Autocomplete className={styles.searchBar} freeSolo
options={placeList}
getOptionLabel={(option) => option.display_name}
onChange={onPlaceSelect}
renderInput={params => (
<CssTextField
{...params}
onChange={onValueChange}
label="Enter Location" variant="outlined" required
/>
)}
/>
I am not pasting onPlaceSelect
function as it executes after I have selected a place from the drop-down and I don't think it is required for this problem.
Below is the visual representation of what is happening...