How to setState the object of the object of state

Viewed 72

Goal: I have two square and I want to change selected square's location. While I'm doing it, I need to change selected square's x-coordinate, y-coordinate, width, and height.

Here is my state which holds the data for square information.

state = {
    gestureState: {},
    thumbSize: 100,
    left: width(100) / 2,
    top: height(100) / 2,
    taggedClothes: {
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
    },
    selectedClothId : 0,
  }

Problem: taggedClothes have two square information and I want to change only selected problem but I'm getting compile error

Here I'm performing setState its taggedClothes[0]

// this.state.selectedColorId = 0
var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
          deep.left = left
          deep.top = top
          deep.thumbSize = thumbSize
          this.setState({
            gestureState: {
              ...gestureState
            },
            taggedClothes[0]: deep  <- Getting Compile Error 
          })

If your have any other suggestion, Please suggest other option!

2 Answers

The key taggedClothes[0] is not valid. You need to spread the taggedClothes and only replace the one that changed:

  var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
  deep.left = left
  deep.top = top
  deep.thumbSize = thumbSize
  this.setState({
    gestureState: {
      ...gestureState
    },
    taggedClothes: {
      ...taggedClothes,
      [this.state.selectedColorId]: deep
    }
  })

You are trying to access your taggedClothes object like an array. change this:

 taggedClothes: { 
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
 },

to that:

 taggedClothes: [ 
      {id:0, left:100, top:100, thumbSize:100}, 
      {id:1, left:200, top:200, thumbSize:200},
 ],

now you should be able to access taggedClothes.

Related