0
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?

Zheng Jie
  • 5
  • 3
  • Hmm, that's weird, on first glance it looks fine. Can you include a bit more code, that shows how your functional component is set up? – Nathan Jun 17 '22 at 19:51
  • It's just a silly mistake, there's nothing wrong with the code. Look at ZomitaKa explanation. – Zheng Jie Jun 17 '22 at 20:07

1 Answers1

2

You have done nothing wrong , this 'problem' happened to many people and they are really thinking there is something worng and the simple answer is ReactJs useState sets its state asynchronously which means the next line which is the console.log() will probably print the value before changing so to verify the value of brandName do it in a useEffect

useEffect(()=>{
   console.log(brandName)
},[brandName])

Check this out: The useState set method is not reflecting a change immediately

ZomitaKa
  • 475
  • 2
  • 7
  • Oh my god, I'm such a fool. I have no idea useState is asynchronous. Thank you for your explanation. – Zheng Jie Jun 17 '22 at 20:06
  • wait, really?? I thought it changed immediately in the execution context but were batched together for a single rerender. TIL. – Nathan Jun 17 '22 at 20:24