PICKAB00
PICKAB00

Reputation: 308

Material UI unable to set default value on Autocomplete

I am using React Hook Form to set the value of gender autocomplete upon loading the data from API. But the autocomplete does not seem to set the data. My main component looks like this:

// this function is used to set the default form values. for now, its just gender value
const setFormValues = () => {
       setValue("gender", {id: 'male', name: 'Male'})
    };

And in useEffect, I am running the above function whenever the data is done loading.

// prerequisites consists of many objects. gender is one of them
useEffect(() => {
        setFormValues();
    }, [prerequisites]);

Here is what the component looks like:

<Controller
        name={name}
        control={control}
        render={({field: {onChange}}) => (
          <Autocomplete
            onChange={(e, data) => onChange(data?.[onChangeAttribute])}
            options={options || []}
            getOptionLabel={(option) => option.name}
            isOptionEqualToValue={(option, value) => option.id === value.id}
            renderInput={(params) => <TextField {...params} placeholder="test" label="test"/>}
          />
        )}
      />

I then went on to the documentation which pointed me to this. Basically, I can pass a default value. I then went on to creating a state and setting that state from the setFormValues() function. The state was being set correctly. But when I pass it to the defaultValue, the value is not being set and instead shows me the error uncontrolled component being used as a controlled component and use it as a controlled component instead.

What I am trying to do:

The idea I had in mind was to set the default value which is coming from an API call on useEffect. Basically, the page is the 'edit' page and I want to show the current selection.

Upvotes: 1

Views: 13088

Answers (2)

Omid_Mirzaee_Yazdi
Omid_Mirzaee_Yazdi

Reputation: 90

Instead of setting the default value try to have a state with the default value you want and then set the value={thestate} so the onChange should change the same state.

Upvotes: 1

knoefel
knoefel

Reputation: 6949

You're missing to set value prop on the <Autocomplete />.

<Controller
  name={name}
  control={control}
  render={({field: {onChange, value}}) => (
    <Autocomplete
      onChange={(e, data) => onChange(data?.[onChangeAttribute])}
      options={options || []}
      value={value}
      getOptionLabel={(option) => option.name}
      isOptionEqualToValue={(option, value) => option.id === value.id}
      renderInput={(params) => <TextField {...params} placeholder="test" label="test"/>
      }
    />      
  )}
/>

Also you can just use RHF's reset, when your API call should return other form values.

useEffect(() => {
  reset(prerequisites);
}, [prerequisites]);

Upvotes: 0

Related Questions