0

I am using React 16 to build a simple e-commerce app. When I delete items from the shopping cart, the order of the items displayed changes even though the original array is not mutated. And the new array is also correctly ordered. Neither are the keys in conflict. They also do not change during the course of the render process.

Here is the cart before removing one quantity from the first item: enter image description here

Here is the cart after removing one quantity from the first item:

enter image description here

As you can see, the item jumps down to the last order.

Here is the removeFromCart code:

export const removeFromCart = item => prevState => {
  let index = prevState.cart.indexOf(item.key)

  console.log('cart before removal', prevState.cart)

  let newCart = [
    ...prevState.cart.slice(0, index),
    ...prevState.cart.slice(index + 1)
  ]

  console.log('cart after removal', newCart)

  return {
    cart: newCart
  }
}

Here is my CartPage component:

function CartPage({ items, onAddOne, onRemoveOne }) {
  return items.length > 0 ? (
    <ul className="CartPage-items">
      {items.map(item => (
        <li key={item.key} className="CartPage-item">
          <Item item={item}>
            <div className="CartItem-controls">
              <button
                onClick={() => onRemoveOne(item)}
                className="CartItem-removeOne"
              >
                &ndash;
              </button>
              <span className="CartItem-count">{item.count}</span>
              <button
                onClick={() => onAddOne(item)}
                className="CartItem-addOne"
              >
                +
              </button>
            </div>
          </Item>
        </li>
      ))}
    </ul>
  ) : (
    <p>Your shopping cart is empty</p>
  )
}

The full code can be viewed here The live app can be seen here

Open the console to see the array order. Please add a bunch of items to the cart and try removing one quantity at the time to see the problem reproduced.

Amit Erandole
  • 11,995
  • 23
  • 65
  • 103

2 Answers2

1

I just looked at your source code. What I can infer from it is that while you are creating cart items object you are using Object.keys(itemCounts) where itemCounts is a javascript object.

Here please note that you will not get the keys in the same order as you would have inserted them. If you want the items to be ordered, you can use arrays instead

Here are some reference links for you

How to iterate javascript object properties in the order they were written

Does JavaScript Guarantee Object Property Order?

Hope it helps

0

A key is the only thing that React uses to identify DOM elements. since you used the index value as key you have to find the specific index of the item where it is, then you modify it and finally ships back to the state in the same order. Otherwise your products will be displayed in the wrong order.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202