-1

I have the following state in my React component:

state = {
        genderRadioClick : false,
        ageRadioClick : false
    }

I have the following function that gets called onChange of every radio button in the component:

_updateRadioButtonValuesObsolte = (e) => {

    let newStateOfCheckboxs = {
        genderRadioClick : Array.from(document.getElementsByName('customer_gender')).some( (elem , idx) => {  return elem.checked  }),
        ageRadioClick : Array.from(document.getElementsByName('customer_age')).some( (elem , idx) => {  return elem.checked  })
    }

    console.log(newStateOfCheckboxs);

    this.setState({
        ...newStateOfCheckboxs
    });

    console.log(this.state);

}

When i check one of the radio button and the following line of code runs:

console.log(newStateOfCheckboxs); // {genderRadioClick: true, ageRadioClick: false}

Which is correct , but the output of the below line:

console.log(this.state);  // {genderRadioClick: false, ageRadioClick: false}

is wrong , Why are the values of the keys in the compomemnt state wrong ? Even though i am updating as below:

this.setState({
            ...newStateOfCheckboxs
        });

What am i doing wrong here ?

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174

1 Answers1

1

setState is an asynchronous function

this.setState({ ...newStateOfCheckboxs }); console.log(this.state);

By this you are expecting state to be immediately updated after setState is called. But you can follow a callback approach

this.setState({
    ...newStateOfCheckboxs
}, function(){
console.log(this.state);
});
Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42