Hello everyone,
A bit of a weird one now. I have a heavily customized Autocomplete due to restrictions and other use-cases. I now have an issue with the filter. It's still displaying all options available. I console.logged the filter result itself and this does correctly work. When I log it I only see the filtered values. THing is, all options stay displayed. None are filtered.
In short;
options.filter()
does it's job right.What's going wrong here? Do I handle something wrong or is something else at play?
<Autocomplete
options={allCountries}
onChange={(event, newValue) => {
if (!newValue || !newValue[1] || !newValue[1].phone) return;
setPrefix(newValue[1].phone);
}}
value={allCountries.find(
(nestedArray) => nestedArray[1].phone === prefix
)}
autoHighlight
getOptionLabel={(option) => `+${option[1].phone}`}
renderOption={(props, option) => (
<Box
component="li"
sx={{ "& > img": { mr: 2, flexShrink: 0 } }}
{...props}
>
<img
width="20"
src={`https://flagcdn.com/w20/${option[0].toLowerCase()}.png`}
/>
{option[1].name} (+{option[1].phone})
</Box>
)}
filterOptions={(options, state) => {
if (state.inputValue === "") return options;
const query = state.inputValue.toLowerCase();
return options.filter((option) => {
return `${option[1].name.toLowerCase()} (+${
option[1].phone
})`.includes(query);
});
}}
renderInput={(params) => (
<TextField
{...params}
label="Prefix"
inputProps={{
...params.inputProps,
}}
/>
)}
/>
As far as I can see you're updating only the value
prop after the prefix has been changed. But, besides that you have to update the inputValue
prop too, which is responsible for the value displayed in the textbox:
const [inputValue, setInputValue] = React.useState('');
...
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
...
const [allCountries, setAllCountries] = useState([
//initial Options
]);
const onChange= (inputValue )=>{
if (inputValue === "") return options;
const query = inputValue.toLowerCase();
let list = options.filter((option) => {
return `${option[1].name.toLowerCase()} (+${
option[1].phone
})`.includes(query);
});
setAllCountries(state=>(list))
}
autocomplete props:
onChange={(e, value) => onChange(value)}