1

I have a multiselect dropdown. whenever I select an option I need to add that data to state. when I click the first option I get data like

[{id:"1", name:"Ind"}]

when I click the second option I get data like (currently two options are selected)

[{id:"1", name:"Ind"}, {id:"2", name:"Aus"}]

this.state = {
    selectedCountries: []
};

in the onChange of multiselect I call the below function

handleChange = (options) => {
    var output = [];
    if(options !== null && options !== undefined){
        console.log(options); //    [{id:"1", name:"Ind"}, {id:"2", name:"Aus"}]
        this.setState(prevState => {
            selectedCountries:options
        });
    }
};

Its not working.

I am expecting it like this

selectedCountries:[
    {
        id:"1",
        name:"Ind"
    },
    {
        id:"2",
        name:"Aus"
    }
]

How to achieve this through reactjs?

Saqib Omer
  • 5,387
  • 7
  • 50
  • 71
Gmv
  • 2,008
  • 6
  • 29
  • 46

1 Answers1

3

Your setState syntax is incorrect

    this.setState({
        selectedCountries:options
    });

You need to make use of updater function only when you need to update the state based on the previous state and in that case you need to return an object from the updater function which you aren't doing

It would look like

    const newlyAddedOption = {id:"3", name:"UK"}
    this.setState(prevState => {
        return { selectedCountries:[...prevState.selectedCountries, newlyAddedOption]}
    });

or

    const newlyAddedOption = {id:"3", name:"UK"}
    this.setState(prevState => ({
        selectedCountries: [...prevState.selectedCountries, newlyAddedOption]
    }));

However this isn't currently useful to you since you get all the options together at once.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • if i select 3 options only 2 values are updated in the state. what could be the reason? – Gmv Dec 27 '17 at 12:04
  • Are you logging those after setting state. You might want to check this as well https://stackoverflow.com/questions/41278385/calling-setstate-doesnt-mutate-state-immediately/41278440#41278440 – Shubham Khatri Dec 27 '17 at 12:04
  • when i select a new option i ll get all the selected data like [{id:"1", name:"Ind"}, {id:"2", name:"Aus"}] – Gmv Dec 27 '17 at 12:09
  • Did you check the question that I linked in my above comment – Shubham Khatri Dec 27 '17 at 13:14