const brands = [
{ key: 1, name: "Chanel" },
{ key: 2, name: "louis Vuitton" },
{ key: 3, name: "Gucci" },
{ key: 4, name: "Dior" },
];
const [brandName, setBrandName] = useState("");
{brands.map((items) => (
<ButtonBase
onClick={() => {
setBrandSelected(!brandSelected);
console.log(items.name);
setBrandName(items.name);
console.log(brandName);
}}
key={items.key}
sx={{ width: "100%", mt: "1%", height: "20%" }}
>
<MDBox
display="flex"
flexDirection="row"
width="100%"
height="100%"
alignItems="center"
justifyContent="flex-start"
sx={{
backgroundColor: "#ffffff",
"&:hover": {
backgroundColor: "#f5ede9",
},
pl: "4%",
}}
>
<MDTypography>{items.name}</MDTypography>
</MDBox>
</ButtonBase>
))}
I have rendered a list of brand names using array.map function and wrap it inside a button. I intend to save the brand name whenever a user clicks the button. First button = Chanel, second button = Louis Vuitton, and so on into the "brandName" variable.
I'm having trouble updating "brandName" using useState function inside the array.map function. It returns an empty string whenever I console log "brandName" after using setBrandName(items.name). However, the correct data is printed if I just do console.log(items.name). What am I missing here? Any ideas?