0

i need your help please :-)

    state = {
        order: {
            createdAt: Date.now(),
            products: [
                {
                    leftInStock: "12",
                    productName: "בלה",
                    productPrice: "120",
                    qtyInOrder: 0
                }
            ],
            totalPrice: 0,
            miniClient: {
                id: '',
                fullName: ''
            }
        },
        client: null,
        isClientSelected: true
    }

and this is the function that should preform the update on the object (need to update qtyInOrder).

    setQtyForProduct = (product, name) => {
        if (name === '+') product.qtyInOrder++
        if (name === '-') {
            if (product.qtyInOrder === 1) return
            else product.qtyInOrder--
        }
        const { products } = this.state.order
        this.setState({ order: { ...this.state.order, products: [...products, product] } }, () => { this.getOrderPrice() })
    }

this is how i pass the values

<div className="order-selected-product-list">
   {this.state.order.products.map((product, _id) => {
      return (
         <div key={_id} className="order-product">
            <div className="order-selected-product-card">
               <div>{product.productName}</div>
               <div>{product.qtyInOrder}</div>
            </div>
            <div className="order-products-qty-btns">
               <div onClick={() => this.setQtyForProduct(product, "+")}>+</div>
               <div onClick={() => this.removeProductFromOrder(product)}>הסר</div>
               <div onClick={() => this.setQtyForProduct(product, "-")}>-</div>
            </div>
         </div>
             )
        })}
</div>

i do get the values right , the only thing i caould not manage to do is update the

I know that is something wrong with my setState function cause it adds the products instead of updating the key in it

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Ori Cohen
  • 1
  • 1
  • `product.qtyInOrder++` this mutates the current state. [Don't do that in React](https://stackoverflow.com/q/37755997/1218980). – Emile Bergeron May 19 '22 at 16:37
  • i would not , i would use the setState if i know how to reach the desired key in the product object. what i need is to know how to write the correct setState in order to fix this – Ori Cohen May 19 '22 at 16:44
  • You're close, you just need to go deeper and [spread each step of the way](https://stackoverflow.com/q/43040721/1218980). Another way would be flattening your state, or splitting it. – Emile Bergeron May 19 '22 at 17:17
  • To update the object within the array: https://stackoverflow.com/q/28121272/1218980 – Emile Bergeron May 19 '22 at 17:18

0 Answers0