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 ?
-
1Please share a codesandbox so we can work together at the same code.bertdida– bertdida2020-09-03 09:27:49 +00:00Commented 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-q22gjshalinds– shalinds2020-09-03 10:45:42 +00:00Commented Sep 3, 2020 at 10:45
Add a comment
|
1 Answer
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}
/>
);
}
4 Comments
shalinds
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 :(
bertdida
@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.shalinds
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
bertdida
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.