Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-ui Autocomplete warning The value provided to Autocomplete is invalid

I am working with React and material-ui.. I just realize i have a warning with the Autocomplete component when i try to submit the form, so i tried to do something really basic just like in the documentation:

let Form = props => {

  return(
        <form noValidate onSubmit={handleSubmit} >
            <Autocomplete
                id="combo-box-demo"
                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" />}
            />

and when i try to submit the form i get the following error:

Material-UI: The value provided to Autocomplete is invalid. None of the options match with {"id":1,"name":"test"}. You can use the getOptionSelected prop to customize the equality test.

I also realize that if i set the options in the state of the component there is no warning (just when they are set like a constant). So i wonder if some of you have any idea of this behavior? thank you so much in advance.

like image 756
Julio Lopez Avatar asked May 22 '20 04:05

Julio Lopez


3 Answers

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}
like image 107
wwwebman Avatar answered Oct 20 '22 04:10

wwwebman


version 5.0

isOptionEqualToValue={(option, value) => option.value === value.value}
like image 41
Laszlo Kovesdi Avatar answered Oct 20 '22 06:10

Laszlo Kovesdi


This Worked,

getOptionSelected={(option, value) => option.value === value.value}

https://github.com/mui-org/material-ui/issues/18514#issuecomment-606854194

like image 43
Mohammed Mudassir Avatar answered Oct 20 '22 04:10

Mohammed Mudassir