I want to have an Autocomplete which supports
- if the initial value has id > 0 then I want the autocomplete to default to the object I have provided
- If the initial value has id <= 0 then I want the autocomplete to be empty a start
When the user select I want the console not to complain
Basically on start page I want them to select a value
When they navigate back to the home page I want this to be pre-populated
This did not look that hard. I have got it to work but it complains on the console. With
a) The value provided to Autocomplete is invalid or
b) a component is changing the uncontrolled value state of autocomplete
The popular answer is to set the value to ” but or null. I cannot use ” as it is an object
When I do not have value this works perfectly well except of course I cannot then have a default value which is not what I want after the user has made their initial select.
export const LeonardCohenAlbumSelect = ({ initialLeonardCohenAlbum, handleLeonardCohenAlbumChanged }: IProps): React.JSX.Element => {
const [selectableValue, setSelectableValue] = React.useState<LeonardCohenAlbum>(initialLeonardCohenAlbum)
const leonardCohenAlbums = useSelector(selectAllLeonardCohenAlbums)
const onChange = (event: SyntheticEvent, value: LeonardCohenAlbum): void => {
setSelectableValue(value)
if (handleLeonardCohenAlbumChanged) handleLeonardCohenAlbumChanged(value)
}
return (
<FormControl fullWidth={true}>
<Autocomplete
value={selectableValue.id > 0 ? selectableValue : null}
options={leonardCohenAlbums}
disablePortal={true}
disableClearable={true}
getOptionLabel={option => option.leonardCohenAlbumLabel}
onChange={onChange}
renderInput={params => (
<TextField
{...params}
inputProps={{ ...params.inputProps, readOnly: true }}
placeholder="Select Album"
label="Album"
/>
)}
/>
</FormControl>
)
}
2
Answers
So after a long search the answer is to change the selected value to allow any.
This lets you now specify specify a null in the value field.
Which is not possible without the null in the selectValue. If you use null and not any in selectValue, value on the autocomplete does not allow null.
issue with handling the initial value and default behavior of the Autocomplete component in your React app. The warning messages you’re encountering are likely related to controlled vs. uncontrolled components.
By maintaining a controlled state and handling the default behavior through the useEffect hook, you should be able to address the console warnings and achieve the desired behavior for your Autocomplete component.