I've been getting "Cannot update during state transition
" errors on my AutoComplete component, and after some searching around I found that it was because of my renderInput
code.
I try to read the input during renderInput
, but I can't edit the state then, so I can't read the input when I need to. It's all very confusing to me.
Is there a way to only execute a method when a value is really selected? EG when Enter is pressed when highlighting something, when an option in the popup is clicked, etc.
Below is the renderInput
code:
public render() {
const { classes } = this.props;
return (
<div className={classes.autoSuggest}>
<Autocomplete
ListboxProps={{ style: { maxHeight: 200, overflow: 'auto' } }}
autoHighlight={true}
disablePortal={false}
options={this.getOptions()}
onClick={(_event, value) => this.onSelect(value)}
renderInput={(input) => { return this.onInput(input);}}
/>
</div>
);
}
private onInput(input: AutocompleteRenderInputParams) {
if (!this.state.alleenUnCodes &&
input.inputProps.value !== undefined &&
input.inputProps.value.toString() !== "" &&
input.inputProps.value.toString().charAt(0) === '/') {
this.setState({alleenUnCodes: true});
}
if (this.state.alleenUnCodes &&
input.inputProps.value !== undefined &&
input.inputProps.value.toString().charAt(0) !== '/') {
this.setState({alleenUnCodes: false});
}
return <TextField {...input} label={'Type GEVI/UN of /UN code (bv 20/1002, of /20)'}/>;
}
EDIT: I found the answer... I tried to read the input to filter my options. However, apparently I can just use the filterOptions param!
I had completely missed the filterOptions
parameter despite reading the React AutoComplete documentation multiple times. It seems that for filtering the option filterOptions is the perfect option!
For those interested, the working code:
filterOptions={(options, state) => {
return options.filter((option) => {
return option.substring(0, state.inputValue.length) === state.inputValue;
});
}}