Cristian Vega Sanchez
Cristian Vega Sanchez

Reputation: 35

SetState dynamicly to modify object values

Hi Im trying to init my buttons state (setState) from a String that give you the key of the button(botones);

var stateButton = "button1-0"

enter image description here

Actual State:

enter image description here

I don't now how write on react state the "state.botones[stateButton]: true" syntax

Upvotes: 0

Views: 60

Answers (4)

Khabir
Khabir

Reputation: 5854

Hi you should not mutate state object. Instead you should use setState with prevState like

constructor(props){
   super(props);
   this.state = {
      user: {}
   }
}

this.setState((prevState) => {
     const updatedUser = {...prevState.user, [target.name]: target.value};
     return { user: updatedUser }; 
   }, () => this.doSomething(this.state.user);
);

Source

Upvotes: 0

Zain Zafar
Zain Zafar

Reputation: 936

this.setState({
 ...this.state
  botones: {
     ...this.state.botones, 
    [stateButton]: true
}});

I believe this should work

Upvotes: 0

cbr
cbr

Reputation: 13642

You'll want to make a copy of the botones object with, for example, spread:

setState({
  ...state,
  botones: {
    ...state.botones,
    [stateButton]: true
  }
})

If you're using a class component instead of a useState hook, you only need to specify botones as React will merge the state keys:

this.setState({
  botones: {
    ...this.state.botones,
    [stateButton]: true
  }
})

Upvotes: 3

Pablo CG
Pablo CG

Reputation: 816

You shouldn't modify the state object, because it must be treated as immutable. What you need to do is to define a new object containing the same content of the existing one, but changing only that button value.

Check: https://reactjs.org/docs/react-component.html#state

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

Upvotes: 0

Related Questions