I am fetching data from an API in order to render a Select box. The value in the select box contains a users details. My problem is that on initial load even when data is fetched correctly a default / initial user is not rendered within the select box even though the data is there.
The onchange event and the select box itself works as expected otherwise. I have added a default value. A key to show the DOM its a new element and unsure what else to try
import { Avatar, Grid, MenuItem, SelectChangeEvent, Select } from "@mui/material";
import {iconMap} from './iconMap.ts'
const SocialSelectDropdown = () => {
const [selectedAccount, setSelectedAccount] = useState<IConnectionData | null>(connectionData?.[0] ?? null)
useEffect(() => {
if (connectionData) {
setSelectedAccount(connectionData?.[0])
}
}, [connectionData])
const handleSelectedConnection = (e: SelectChangeEvent<string | unknown>) => {
setSelectedAccount((prevState: IConnectionData | null) => {
const selectedSocial = connectionData?.find((connection) => connection?.id === e?.target?.value);
return selectedSocial || prevState;
});
};
if (!selectedAccount?.id) {
return <Loader />
}
return (
<Grid item xs={12}>
<Select
key={selectedAccount?.id}
size="small"
sx={{ maxWidth: "fit-content" }}
value={selectedAccount?.id}
onChange={handleSelectedConnection}
>
{connectionData
?.filter((item: any) => !["facebook_user"].includes(item?.platform))
?.filter((item) => (role_id === 5 ? item : item?.platform !== "linkedin"))
?.map((social: IConnectionData, index: number) => (
<MenuItem key={social?.id} selected={selectedAccount?.id === social?.id} value={social.id}>
<Grid container flexDirection="row" alignItems="center" gap={1}>
<Grid item position="relative">
<Avatar src={social?.profile_pic_url} />
<Grid item position="absolute" bottom={-5} right={-5}>
<GetPlatformIcon platform_id={iconMap(social)} size={20} />
</Grid>
</Grid>
<Typography>
{social?.username}
</Typography>
</Grid>
</MenuItem>
))}
</Select>
</Grid>
);
};
export default SocialSelectDropdown
wn;