Im new to react and I have a question about select component of material ui.
The thing is like this, I have a funcionality that is for creating and editing an User, this User is an object, it has primary key and some data, between this data there is a relation with other object that is a role, so in this case I use a Select component to select the role.
So, I have the role list that I bring from the backend:
const [rolList, setRolList] = React.useState([]);
const searchRoles = async () => {
try {
setRolList(await api.post('/v1/roles/buscar', filtroRol));
} catch (error) {
snackbar.showMessage(error, "error");
}
}
And the select component that is inside a formik:
<Mui.Select
label="Role"
value={values.usuRolPk}
onChange={(opt) =>{handleChange(opt);
}}
>
<Mui.MenuItem disabled key={0} value=''>
Select role
</Mui.MenuItem>
{rolList.map((e) => {
return <Mui.MenuItem key={e.rolPk} value={e.rolPk}>{e.rolName}</Mui.MenuItem>;
})}
</Mui.Select>
As you can see, for the value of the select I use the pk of role, so when the user is persisted I have to search in the list of roles and atach the selected object to the users object and send it to the backend.
Something like this (usuRolPk is the value of the select, usuRol is the relation with object role):
const save = async (values) => {
try {
if(values.usuRolPk==null){
values.usrRole=null;
}else{
values.usrRole=rolList.filter(element=>''+element.rolPk==values.usuRolPk)[0];
}
...
if (values.usrPk == null) {
await api.post('/v1/users', values);
} else {
await api.put('/v1/users/' + values.usrPk, values);
}
handleClose();
snackbar.showMessage("GUARDADO_CORRECTO", "success")
} catch (error) {
snackbar.showMessage(error, 'error');
}
return;
}
The thing is, I want to skip that last step of having to search in the list of roles with the selected Pk.
Is there a way of working just with the object as the selected value instead of the pk? I tried just changing the value to have the whole object like this:
<Mui.Select
label="role"
value={values.usuRol}
onChange={(opt) =>{handleChange(opt);
}}
>
<Mui.MenuItem disabled key={0} value=''>
Select role
</Mui.MenuItem>
{rolList.map((e) => {
return <Mui.MenuItem key={e.rolPk} value={e}>{e.rolName}</Mui.MenuItem>;
})}
</Mui.Select>
This works just when Im creating a new object, but when I try to edit an object that already exists and already has a role, when I pass the role to the select It says something like I initialize the Select with a value that doesnt exist in the list of roles.
Is there a way to achieve this?
Thanks!