skip to Main Content

I’m having some trouble here on a simple dropdown select from MaterialUI/React that although I am able to update the label for the item I am clicking on, the state is still stuck on the previous value. Open the console terminal to see what I mean.

This will/can create issues when I want another set of options to open depeding on the state selected. For example, if I click on "Blues & Jazz", I should be able to get a set of options that correspond to subgenres of "Blues & Jazz), Not subgenres of whatever else was clicked before.

P.S. For brevity, I didn’t add the submenus options. I can probably handle that if I can get the state to update onclick

import React, { useState } from "react";
import { Box, FormControl, MenuItem, Select } from "@mui/material";

export const wbrselectors = {
  sections: ["Rock", "Soul", "Hip Hop & R&B", "Blues & Jazz", "Classical"]
};

export default function App() {
  const [sectionone, setSectionOne] = useState("Rock");

  const onSectionOneSelectChange = ({ target }) => {
    const value = target.value;

    setSectionOne(value);

    console.log("value:", value, ", sectionone:", sectionone);
  };

  return (
    <Box>
      <FormControl fullWidth size="small">
        <Select
          component="dropdown"
          value={sectionone}
          name="sections"
          defaultValue=""
          onChange={onSectionOneSelectChange}
        >
          {wbrselectors.sections.map((item, index) => (
            <MenuItem key={index} value={item}>
              {item}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
}

Here’s a link in sandbox. Thanks in advanced

2

Answers


  1. Setting state is async. You need to use another hook to react upon the changes on state:

      useEffect(() => {
        console.log("sectionone:", sectionone);
      }, [sectionone]);
    

    Here, the function we provide to useEffect hook will run when sectionone changes.

    Login or Signup to reply.
  2. This is actually working as expected, the state update is async in nature, and React might batch multiple setState() updates for better performance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search