0

For some reason I cannot set the state in React onClick. It works if I hard-code in "shape1" in place of "shape", but I want to loop through each key and set it dynamically as there is a variable amount of shapes.

resetColors() {
  Object.keys(this.state).forEach(shape => {
    this.setState({shape: 'black'})
  })
}
2
  • I guess resetColors() { Object.keys(this.state).forEach(shape => { this.setState({[shape]: 'black'}) }) } should work for you Commented May 22, 2017 at 4:00
  • Possible duplicate of using immutability-helper to $merge an array Commented May 22, 2017 at 4:03

1 Answer 1

2

The code in your question would always just set a single "shape" state value to "black" and doesn't assign multiple shape values. I think you are expecting that the "shape" variable passed into the array will be used inside the curly brace as the name of the variable to set. Easy mistake to make, but in JS, the name to the left of the colon is static text that is unaffected by the variables you have in scope.

From your description, I believe you have used state names like "shape1", "shape2". So maybe code like this would work:

resetColors() {
  const valuesToSet = {};
  Object.keys(this.state).forEach(keyName) => {
    valuesToSet[keyName] = 'black'; 
  });
  this.setState(valuesToSet);
}

But to be honest, that's a risky and weird way to code it. Risky, because if you add another state variable later that isn't meant to be part of shapes, it will get overwritten. Weird, because you are reinventing the oft-used functionality of arrays with your variable naming.

I instead recommend your 'shape1', 'shape2', etc. state values be converted to a single 'shapes' array to be stored in state. Then you can use code like this:

resetColors() {
  const newShapes = this.state.shapes.map( (shape) => 'black' );
  this.setState({ shapes: newShapes });
}
Sign up to request clarification or add additional context in comments.

Comments

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.