0

what im trying to achieve is to be able to use the setState method to set an object as the state. However im facing some difficulty in doing so.

This is the final endproduct (state) which i was to achieve

  state_class_mapping: {
        {1} ,
        rect: {
          fill: "deepskyblue"
        },
        label: {
          stroke: "white"
        }

This values are obtained from different areas , the rect and label is preset in my state upon initializing:

 constructor(props) {
super(props)

this.state = {
  selected_state: null,
  state_class_mapping: {},
  selected_state_class: {         #<---- here 
    rect: {
      fill: "deepskyblue"
    },
    label: {
      stroke: "white"
    }
  },
  default_state_class: {     #<---- or here depending 
    rect: {
      fill: "#dddd"
    },
    label: {
      stroke: "black"
    }
  }
  }

The integer value is actually the ID of the object that i have clicked . Upon clicking onto this object , i would run some functions to set the "selected_state" .

My issue is that i have issues creating the state_class_mapping state as its more complex than just setting a static key and value.

What i would envision the way to set would be :

this.setState({state_class_mapping:{
    {this.state.selected_state},
    {this.state.default_state_class}
  })
  }
}

But ofcourse my editor shows that it is illegal to do it this way. May i know what is the proper way of doing this?

neowenshun
  • 860
  • 1
  • 7
  • 21

1 Answers1

4

I just looked at your code and I think you missed some snippets. First you need to declare correct object according to exact type you declared in state definition. So in my opinion you need to try like this.

this.setState({state_class_mapping: {
   idValue, 
   ...this.state.selected_state, 
   ...this.state.default_state_class
}});

You didn't declare state_class_mapping type as { {}, [{}]} so your code isn't working. You declared as this type {{}, {}}

Hope this helps you to understand.

Bojan
  • 637
  • 7
  • 17
  • hey ! I've tried it , there seems to be a parsing error , im not sure if this is because its illegal to do so in React , https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react – neowenshun May 27 '20 at 06:54
  • Alright , it works now , thank you so much , i realize it would work without the {} on idValue – neowenshun May 27 '20 at 06:57
  • Sounds great it helped you. I updated answer. Thanks – Bojan May 27 '20 at 07:11