I am new to react and material UI and struggling to load Autocomplete component options dynamically.
Initially, I am setting empty array as initial option until data is fetched from the database. Once I get my data I update the Autocomplete options with my data and it's working but at the same time I am getting the following warning
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
My code
const [listItems, setListItems] = useState([]);
const {formik, items} = props;
const handleGetOptionSelected = (option, value) => {
if (!items) {
return {};
}
return option.id === value.id;
};
const handleGetOptionLabel = (option) => {
if (!items) {
return 'No Options';
}
return option.name;
};
useEffect(() => {
if (items) {
setListItems(items);
}
}, [items]);
return (
<Autocomplete
className={classes.autoComplete}
multiple
id="tags-standard"
options={listItems}
getOptionLabel={(option) => handleGetOptionLabel(option)}
getOptionSelected={(option, value) => handleGetOptionSelected(option, value)}
onChange={(event, selectedValues) => {
formik.setFieldValue(
"tag_ids",
getCollectionColumn(selectedValues, 'id'),
false
);
}}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
placeholder="select tags"
name="tag_ids"
error={formik.touched.tag_ids && Boolean(formik.errors.tag_ids)}
helperText={formik.touched.tag_ids && formik.errors.tag_ids}
/>
)}
/>
);