0

I have a react component that I have created. In this component, I call a function that updates the state generically:

updateCheckbox: function(name, value) {
    this.setState({name: value});
},

I have checked the value of this function and I see that the correct value is getting called and set. The render function is then called, because the state has just been set. When I go inside the render function, the state has not been updated.

I realized this is because I have updated the state generically. If I put the actual name of the state in the setState function, then everything is updated as it should.

Does anyone know a workaround for this?

jhamm
  • 24,124
  • 39
  • 105
  • 179

1 Answers1

1

You need to use Computed property name(which is added in ECMA 6) to use the value stored inside name variable

updateCheckbox: function(name, value) {
    this.setState({[name]: value});
},

OR the bracket notation for wider browser support

updateCheckbox: function(name, value) {
    var temp={};
    temp[name]=value;
    this.setState(temp);
},
bugwheels94
  • 30,681
  • 3
  • 39
  • 60