I have a brand object with the field cat_id, on page load categories
load into autocomplete select. Now I want to set category id as a
value with a category option in autocomplete and also set cat_id
from the autocomplete option value onChange.
const handleChange = (e) => {
const { name, value } = e.target;
setBrand({
...brand,
[name]: value,
});
};
<Autocomplete
getOptionSelected={(option, value) => option.category_name === value.id}
getOptionLabel={(option) => option.category_name}
name="cat_id"
onInputChange={handleChange}
options={categories}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
label="Category"
fullWidth
variant="outlined"
required
InputProps={{
...params.InputProps,
endAdornment: (
<Fragment>
{" "}
{loading ? <CircularProgress color="inherit" /> : null}{" "}
{params.InputProps.endAdornment}
</Fragment>
),
}}
/>
)}
/>;
After waiting a while for the help. I manage to solve this but I'm not sure is this a recommended way. I directly set the field value onChange and didn't use handleChange function.
<Autocomplete
getOptionSelected={(option, value) => option.category_name === value.id}
getOptionLabel={(option) => option.category_name}
name="cat_id"
options={categories}
loading={loading}
onChange={(e,option) => setBrand({...brand,cat_id: option.id,})}
renderInput={(params) => (
<TextField
{...params}
label="Category"
fullWidth
variant="outlined"
required
InputProps={{
...params.InputProps,
endAdornment: (
<Fragment>
{" "}
{loading ? <CircularProgress color="inherit" /> : null}{" "}
{params.InputProps.endAdornment}
</Fragment>
),
}}
/>
)}
/>;