0

I am using a Material UI Select Component to render a simple drop down menu, with its value as a state declares using the useState method.

    const [collaboratingTeams, setCollaboratingTeams] = useState([])

The below code is of the Select Component, with its value and the corresponsing handler function in its onChange prop.

                 <Select
                    validators={["required"]}
                    errorMessages={["this field is required"]}
                    select
                    multiple
                    variant="outlined"
                    value={collaboratingTeams}
                    name="collaboratingTeams"
                    onChange={(e) => handleSelectCollaboratingTeams(e)}
                    helperText="Select Collaborating Teams &nbsp; &nbsp;"
                    
                >
                    {arrTeams.map((option, index) => (
                    <MenuItem
                   key={option.teamId}
                  value={option.teamId}
                 variant="outlined"
                 >
               <Checkbox
              checked={collaboratingTeams.indexOf(option.teamId) !== -1}
            />
           <ListItemText primary={option.teamValue} />
        </MenuItem>
        ))}
      </Select>

The below code is the function that triggers when a drop down data is changed. This function sets the state, which should then technically update the Select's selected options.

const handleSelectCollaboratingTeams =(e)=>{
        setCollaboratingTeams(e.target.value)
 }

The issue is, the setCollaboratingTeams method isn't updating the state only. I understand that the setstate method in hooks works so coz of its asynchronous nature but at some point it should display up right. Don't understand where I'm going wrong.

I expect the collaboratingTeams array to be updated with a new value when a new value is selected by the user.

  • i have a guts feeling that the interface of this Select isn't `e`. Can you put a console.log inside `handleSelectCollaboratingTeams`? – windmaomao Sep 18 '21 at 22:14

2 Answers2

0

dont use arrow function with onchange it often used when we need to pass id or some other data

Adib Sadeghi
  • 106
  • 1
  • 1
  • 5
0

you should define the new state for storing the selected item.

Example for class component:

  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

Example for functional component(using React-hook):

const [selectedOption, setSelectedOption] = useState(null);
  handleChange = selectedOption => {
    setSelectedOption(selectedOption);
  };
Yasin Br
  • 1,675
  • 1
  • 6
  • 16
  • 1
    Thanks a lot for the answer. I fixed it by changing the state declaration to null. Moreover, the state was getting updated, but I wasn't using the correct state to get the display on the output screen. Apologies for the late response. – V.J. Karthik Mar 28 '22 at 20:04