-1

I followed the same pattern mentioned in this question but the difference is I'm passing the 'options' as 'props.CountryList' from another component. Can someone please let me know what are the changes I need to do when I pass the 'options' as a props ?

2
  • 1
    Please share a codesandbox so we can work together at the same code. Commented Sep 3, 2020 at 9:27
  • @bertdida : Here is the sample codesandbox : Would be great if you can help me on this codesandbox.io/s/charming-snyder-q22gj Commented Sep 3, 2020 at 10:45

1 Answer 1

1

You are passing an empty array as defaultValue value in your Controller - then you are using that as the value for Autocomplete. I also don't think you need the defaultValue in Autocomplete.

Anyways, the code below should work

export default function AutoSelect({ options, selectedValue }) {
  const { control, setValue } = useForm();

  if (options.length === 0) {
    return null;
  }

  const defaultValue = options.find((i) => i.value === selectedValue);

  return (
    <Controller
      render={(props) => (
        <Autocomplete
          options={options}
          getOptionLabel={(option) => option.label}
          value={props.value}
          onChange={(e, values) => setValue("food", values)}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Choose food"
              name={props.name}
              placeholder="Choose food"
              variant="outlined"
              fullWidth
            />
          )}
        />
      )}
      control={control}
      name="food"
      defaultValue={defaultValue}
    />
  );
}

Edit suspicious-bartik-qlkp2

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for the explanation. Still defaultValue is not showing. I'm calling separate two APIs to get the "options" and "selectedValue". May be the autocomplete component render before selectedValue (defaultValue) is set ? Already spent one day on this , no luck :(
@shalinds that's weird. I think the issue is on you Parent component. I updated the codesandbox to simulate the API call. Please check it out.
Seems something wrong with the Parent component. I copied the exact CodeSandbox sample and pasted in my solution , DeafultValue is not displaying. In Parent component I have 10-15 sub components which calls different APIs and it take sometime to load data too,as mentioned AutoComplete component is getting render before I set the DeafultValue it seems
Yea. That's why (if you notice), I rendered a loading spinner while API call is not resolved yet, this avoids rendering AutoComplete component while fetching is still in progress.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.