import React, { useCallback, useEffect, useState } from "react";
import Autocomplete from '@mui/lab/Autocomplete';
import TextField from '@mui/material/TextField';
import debounce from "lodash/debounce";
import { getOptionsAsync } from "./options";
function App() {
const [options, setOptions] = useState([]);
const [inputValue, setInputValue] = React.useState("");
const getOptionsDelayed = useCallback(
debounce((text, callback) => {
setOptions([]);
getOptionsAsync(text).then(callback);
}, 200),
[]
);
useEffect(() => {
getOptionsDelayed(inputValue, (filteredOptions) => {
setOptions(filteredOptions);
});
}, [inputValue, getOptionsDelayed]);
return (
<Autocomplete
options={options}
getOptionLabel={(option) => option.title}
filterOptions={(x) => x} // disable filtering on client
loading={options.length === 0}
onInputChange={(e, newInputValue) => setInputValue(newInputValue)}
renderInput={(params) => <TextField {...params} label="Combo box" />}
/>
);
}
const handleSearch = () => { // ... }
const handleSearchDelayed = debounce(handleSearch, 50);
handleSearchDelayed();
handleSearchDelayed();
handleSearchDelayed();
// handleSearchDelayed is called 3 times but handleSearch will only be called 1 time
// 50ms later
import debounce from 'lodash/debounce
import _ from 'lodash';
...
doSearch(text) {
// Your normal handler here
}
...
// Delay autocomplete until 500 ms after use stops typing
<AutoComplete
onUpdateInput={_.debounce((value) => doSearch(value), 500)}
...
/>