I am using MUI autocomplete multi-select. I am trying to get the one selected option by the user, but I can only achieve the list of multiple selected values. The selected value should be an object containing id and typeName, but it returns the array of selected objects, not the one that I just selected right now.
I tried slicing the array, and it works in selection but not when I deselect any option. On the other hand, I tried with semicolon-separated string but I can't see any help from that
Here is my autocomplete multi-select component;
export default function MultiSelectCategoryDropdown({
names,
defaultValue,
setFieldValue,
label,
setValues,
values,
}) {
const handleCategoryChange = (setFieldValue, value, values) => {
const valueToSave = value.map((itm) => itm.typeName).join(";");
console.log(valueToSave);
const currentSelection = value.slice(-1).pop();
console.log(currentSelection);
setFieldValue("categories", value);
// const indexToRemove = values.categoriesAttributes.findIndex((obj) => {
// return (
// obj.reimbursementType &&
// obj.reimbursementType.typename === value.typeName
// );
// });
// if (indexToRemove !== -1) {
// values.categoriesAttributes.splice(indexToRemove, 1);
// } else {
// values.categoriesAttributes.push({
// totalAllowedLimit: 0,
// allocationEndDate: "",
// reimbursementType: value,
// });
// }
};
return (
<div>
<Autocomplete
sx={addInputStyles}
multiple
id="tags-standard"
options={names}
getOptionLabel={(option) => option?.typeName}
defaultValue={defaultValue}
disableCloseOnSelect
onChange={(e, value) => {
handleCategoryChange(setFieldValue, value, values);
}}
renderOption={(props, option, { selected }) => (
<MenuItem
key={option}
value={option}
sx={{ justifyContent: "space-between" }}
{...props}
>
{option?.typeName}
{selected ? <CheckIcon color="info" /> : null}
</MenuItem>
)}
renderInput={(params) => (
<TextField {...params} variant="outlined" label={label} />
)}
/>
</div>
);
}