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?

3
  • Change this.setState(prevState => { selectedCountries:options }); to this.setState({selectedCountries: options}) Commented Dec 27, 2017 at 12:00
  • That's not JSON but an array of objects. Commented Dec 27, 2017 at 12:01
  • its ok.array of objects. Commented Dec 27, 2017 at 12:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

if i select 3 options only 2 values are updated in the state. what could be the reason?
Are you logging those after setting state. You might want to check this as well stackoverflow.com/questions/41278385/…
when i select a new option i ll get all the selected data like [{id:"1", name:"Ind"}, {id:"2", name:"Aus"}]
Did you check the question that I linked in my above comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.