How to get the count of the filtered options from MUI 5 Autocomplete component? (without changing the default behaviour of the prop filterOptions)
How to get the count of the filtered options from MUI 5 Autocomplete component? (without changing the default behaviour of the prop filterOptions)
You can create a wrapper of filterOptions callback by using createFilterOption to create a default value like the one that is used internally and add your additional code to check for the result length:
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import Autocomplete, { createFilterOptions } from '@mui/material/Autocomplete';
const _filterOptions = createFilterOptions();
export default function ComboBox() {
const [optionCount, setOptionCount] = React.useState(0);
const filterOptions = React.useCallback((options, state) => {
const results = _filterOptions(options, state);
if (optionCount !== results.length) {
setOptionCount(results.length);
}
return results;
}, []);
return (
<>
<Typography mb={2}>Option count: {optionCount}</Typography>
<Autocomplete
filterOptions={filterOptions}
options={top100Films}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
/>
</>
);
}
I was using the solution propsed by NearHuscarl and although it worked like a charm, there was this warning from react that kept popping up
Cannot update a component while rendering a different component
So what I did was to use a ref to store the count
const currentViewOptions = useRef(0);
// Instead of: setOptionCount(results.length);
currentViewOptions.current = results.length;
And it worked like a charm. In case anyone comes here with the same problem.