Material-ui Autocomplete warning The value provided to Autocomplete is invalid
Basically the reason why you get the warning is a default implementation of getOptionSelected
in version 4.x.x:
getOptionSelected = (option, value) => option === value
In your case, selecting a value the following comparison happens:
// option === value:{id:1, name:"test"} === {id:1, name:"test"} // false
Obviously, it can be true
in some circumstances. In this particular case, it's false
because of objects pointing to the different instances.
Solution! You have to overwrite getOptionSelected
implementation:
<Autocomplete getOptionSelected={(option, value) => option.id === value.id} ...otherProps/>
[Update]Note, in version 5.x.x the prop was renamed:
- getOptionSelected={(option, value) => option.id === value.id}+ isOptionEqualToValue={(option, value) => option.id === value.id}
This Worked,
getOptionSelected={(option, value) => option.value === value.value}
https://github.com/mui-org/material-ui/issues/18514#issuecomment-606854194
I think you should not use <form>
to wrap AutoComplete
component. You should set value for AutoComplete
and use a function to handle on click button to submit.
Try this:
let Form = props => { const [value, setValue] = useState({}) const handleOnSubmit = (value) => { setValue(value) ... } return( <div> <Autocomplete id="combo-box-demo" value={value} options={[{id:1,name:"test"},{id:2, name:"test2"}]} getOptionLabel={(option) => option.name} style={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />} /> <Button onClick={() => handleOnSubmit(value)}>Submit</Button> </div> )}