N
N
nivaech2019-06-26 08:16:13
JavaScript
nivaech, 2019-06-26 08:16:13

Why does the value of the state object not change?

There is state, and this one stateis an object.

state = {
    productToCart: {
      size: '',
      color: ''
    }
  }

Before submitting an item to the cart, the user must select the size and color that goes into the state.
This is how the code for choosing the size and color looks like:
{itemSizes.map((size, index) => {
     return (
       <li key={index} className={"filter-item " + (this.state.productToCart.size === size ? "filter-active" : null)} onClick={() => 
       {this.pickSize(size)}}> {size} </li>
    )
   }
 )}
...
{itemColors.map((color, index) => {
     return (
       <li key={index} className={"filter-item " + (this.state.productToCart.color === color ? "filter-active" : null)} onClick={() => 
       {this.pickColor(color)}}> {color} </li>
    )
   }
 )}

Here are the functions that set the state value:
pickSize = (size) => {
    this.setState({
      productToCart: {
        size: size
      }
    })
   }
...
pickColor = (color) => {
    this.setState({
      productToCart: {
        color: color
      }
    })
   }

As a result, only the state of either the color or the size is updated. If you output the result to the console, only the last modified is displayed state, but not both at the same time, because the previous value is replaced by a new one. I clicked on the size - it shows only the size, on the color - only the selected color is displayed. Why are both the first and the second not displayed at the same time, because the functions change, in fact, different values ​​and do not interact with each other in any way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-26
@nivaech

setState only does a superficial merge, if you need to update nested objects, you should copy all their properties:

this.setState({
  productToCart: {
    ...this.state.productToCart,
    color,
  },
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question