Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

adding debounce in autocomplete material ui

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" />}
    />
  );
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #adding #debounce #autocomplete #material #ui
ADD COMMENT
Topic
Name
2+3 =