skip to Main Content

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


  1. Chosen as BEST ANSWER

    So after a long search the answer is to change the selected value to allow any.

    const [selectedValue, setSelectedValue] = React.useState<LeonardCohenAlbum | any>(
    initialLeonardCohenAlbum.id > 0 ? initialLeonardCohenAlbum : null)
    

    This lets you now specify specify a null in the value field.

                 <Autocomplete
                    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
                    value={selectedValue || null}
                    multiple={false}
                    ....
    

    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.


  2. 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.

    import React, { useState, useEffect } from 'react';
    import { Autocomplete } from '@mui/material';
    import { useSelector } from 'react-redux';
    import TextField from '@mui/material/TextField';
    import FormControl from '@mui/material/FormControl';
    
    export const LeonardCohenAlbumSelect = ({ initialLeonardCohenAlbum, handleLeonardCohenAlbumChanged }) => {
      const leonardCohenAlbums = useSelector(selectAllLeonardCohenAlbums);
      
      const [selectableValue, setSelectableValue] = useState(null);
    
      useEffect(() => {
        if (initialLeonardCohenAlbum && initialLeonardCohenAlbum.id > 0) {
          setSelectableValue(initialLeonardCohenAlbum);
        }
      }, [initialLeonardCohenAlbum]);
    
      const onChange = (event, value) => {
        setSelectableValue(value);
        if (handleLeonardCohenAlbumChanged) handleLeonardCohenAlbumChanged(value);
      };
    
      return (
        <FormControl fullWidth={true}>
          <Autocomplete
            value={selectableValue}
            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>
      );
    };
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search