[AutoComplete] - Load value asynchronously does not set selected value
See original GitHub issueWhen I have value after Autocomplete is rendered (originated from an async call), the value is not set as selected one.
- The issue is present in the latest release.
- I have searched the issues of this repository and believe that this is not a duplicate.
Current Behavior 😯
“selected value” is empty when value
is loaded asynchronously
Expected Behavior 🤔
After I get data asynchronously, value
should be selected
Steps to Reproduce 🕹
https://codesandbox.io/s/hardcore-wind-6pjlc
use getAsyncValue to see the issue
Context 🔦
When I have a list of options and I need to have a selected value (e.g from a list of countries, I want USA to be selected already), if my list of countries is an array of objects [{key: 1, value: "USA"}, {key: 1, value: "Japan"}, {key: 1, value: "Belgium"}]
and, BEFORE rendering Autocomplete, I pass {key: 1, value: "USA"}
, it works and USA is shown as selected but, if I call a api to retrieve a user and then pass user.country
( = {key: 1, value: "USA"}
) (which will happen AFTER Autocomplete is rendered) , it does not work, no data is selected and gives me that controlled/uncontrolled warning.
As I just need to show what was selected before, I don’t need a controlled autocomplete and I thought of using defaultValue
to do such a thing…In this case I would pass only USA
as defaultValue
and everything would be fine. Now I can only manage to achieve this if I setup everything BEFORE rendering Autocomplete, which for the UI is weird as I won’t be able to see the autocomplete until I have my data (which I also don’t think it’s necessary)
Basically, I need what getOptionSelected
does but getOptionSelected
only triggers onChange
I don’t know if this is indeed an issue or if I just don’t know how to use Autocomplete properly, if the later is true, I apologize in advance. I have been struggling a lot to use Autocomplete properly in my project and from time to time I end up with some kind of undesirable behavior.
Thanks for considering my request.
Regards,
Your Environment 🌎
Same as codesand
Tech | Version |
---|---|
Material-UI | latest |
React | latest |
Browser | Chrome |
TypeScript | |
OS | Windows |
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:8 (3 by maintainers)
Top GitHub Comments
FWIW, I’ve run into this as well, and it appears to be a bug, or is an unintuitive behavior that (at the very least) needs to be mentioned/addressed in the demo showing how to use async requests with
<Autocomplete>
.If
<Autocomplete>
doesn’t work like any other form control that you can initialize with avalue
, that needs to be mentioned somewhere.I don’t know why, but i have realized it’s because the selected value must be obtained from the same object. I’m not very clear on it but i did this and it worked for me. I work with React.