Demystifying Errors in MUI Autocomplete — part — II
Before reading this, please read this part I. It will give you some basic concepts in MUI Autocomplete.
We know that displayed value in options would be primitives(string, number etc). Input to the options can be non-primitive (array of objects). For any practical purposes like sending data to APIs or other functions, we need an original data structure.
Before deep dive, let me introduce you to two props onChange and onInputChange.Both take exact parameters (event, value and reason)
onChange — invoked whenever you select the display options in the popup.
onInputChange — invoked whenever you type in search field.
<Autocomplete
options={top100Films}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
onChange={(event, value, reason) => console.log("onChange", value)}
onInputChange={(event, value, reason) => console.log("onInputChange",value)}
/>

Notice when the option is selected, both onChange and onInputChange has the same value. Things get interesting when I type in the search field.

When I type in the search field, only onInputChange value changes.OnChange remains null. Therefore rule is
onChange is a function of popup options whereas onInputChange is a function of Searchfield value
So whenever I need a non-primitive format i.e.objects, I should use onChange values.
<Autocomplete
id="country-select-demo"
sx={{ width: 300 }}
options={countries}
getOptionLabel={option => option.name}
onChange={(event,value,reason) => console.log(value)}
renderInput={(params) => (
<TextField {...params}
label="Choose a country"
/>
)}
/>
);
}const countries = [
{ code: "AD", name: "Andorra", phone: "376" },
{ code: "AI", name: "Anguilla", phone: "1-264" },
{ code: "AL", name: "Albania", phone: "355" },
{ code: "AM", name: "Armenia", phone: "374" },
{ code: "AO", name: "Angola", phone: "244" },
{ code: "AQ", name: "Antarctica", phone: "672" },
{ code: "AR", name: "Argentina", phone: "54" },
{ code: "AS", name: "American Samoa", phone: "1-684" },
{ code: "AT", name: "Austria", phone: "43" }
];

Notice here onChange value return the whole object containing the name ‘Andorra’.We can use this object for API’s and functions. This is one of the important features in MUI Autocomplete which makes it complete. I hope this is helpful.