5

I have a State of objects in an Array (in my Redux Reducer).

const initialState = {
      items: [
        { id: 1, dish: "General Chicken", price: 12.1, quantity: 0 },
       { id: 2, dish: "Chicken & Broccoli", price: 10.76, quantity: 0 },
        { id: 3, dish: "Mandaran Combination", price: 15.25, quantity: 0 },
        { id: 4, dish: "Szechuan Chicken", price: 9.5, quantity: 0 }
      ],
      addedItems: [],
     total: 0
    };

I have an action to add 1 to the quantity of an object, such as {id:1, dish: Generals Chicken, price: 10.76, quantity:0} when a button in clicked in Cart.jsx. Here's the first Reducer I tried using the spread operator:

case "ADD_QUANTITY":
  let existing_item = state.addedItems.find(
    item => action.payload === item.id
  );

  return {
    ...state,
    addedItems: [
      ...state.addedItems,
      { ...existing_item, quantity: existing_item.quantity + 1 }
    ]
  };

This didn't work, instead of adding 1 to the quantity, it added another object with the quantity set to 2. . .So, I tried using Map like this

case "ADD_QUANTITY":
  return {
    ...state,
    addedItems: state.addedItems.map(item =>
      item.id === action.payload
        ? { ...item, quantity: item.quantity + 1 }
        : item
    )
  };

And this worked correctly. My question is, why didn't the spread operator work? As far as I can tell, it should do the same thing as the Map?

Chris Kavanagh
  • 451
  • 1
  • 5
  • 15

3 Answers3

4

The two pieces of code are quite different.

The first one creates a new array out of state.addedItems and the new object { ...existing_item, quantity: existing_item.quantity + 1 }, and then assigns that array to the addedItems property of the state.

The second piece of code iterates addedItems and if it finds an element with the same id as the payload, it creates a new object { ...item, quantity: item.quantity + 1 } and returns that one, instead of the original item from the array.

Thus, even though both approaches create a new array, the first one has an extra object compared to the original, while the second has an object with a modified property.

Clarity
  • 10,730
  • 2
  • 25
  • 35
2

Its because in your spread example, its has no way to tell which object it should overwrite. So it doesn't operate quite the same as some other examples you might see. Consider the following:

If you had an object like this:

let test = { a: 'first', b: 'second' }

Then doing spread like this would work:

let newTest = {...test, b: 'third' }

The reason is you are specifying that b should be overwritten.

When you try to create the same effect with an array of objects, you can't specify the key. So what you're actually doing is just appending the new object to the end of the array.

In the map example, you are checking the object contents and returning a different object based on if it matches your condition, so you know which object to overwrite.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
2

The spread syntax, when used in an array literal context, does not reproduce the keys (the indexes), but just the values. As opposed to the spread syntax in an object literal context, which produces key/value pairs. The latter allows previous entries to be overruled by a new entry, having the same key, but the first does not have this behaviour: it always spreads all values without regards for indexes.

When replacing an element in an array, while copying it, you need to:

  • know the index at which the substitution should be performed, and
  • ensure that the copy is an instance of Array, and not just a plain object

You can use findIndex and Object.assign([], ) for addressing those needs:

case "ADD_QUANTITY":
  let index = state.addedItems.findIndex(
    item => action.payload === item.id
  );
  existing_item = state.addedItems[index];

  return {
    ...state,
    addedItems: Object.assign([], state.addedItems, {
      [index]: { ...existing_item, quantity: existing_item.quantity + 1 }
    })
  }
trincot
  • 317,000
  • 35
  • 244
  • 286
  • So, the obj is being updated correctly (using spread), but the element/obj in the array can't be overwritten because it's an array, and therefore no key to find it? – Chris Kavanagh Jan 22 '20 at 20:50
  • It's just that the spread syntax means something different in an object literal, than in an array literal. Yes, in an array literal, the spread syntax just *adds* values to the end of the array, using new, incremental indexes. In an object spread, the key determines whether it is really a new entry, or an update of an entry that was already spread. – trincot Jan 22 '20 at 21:01
  • Also there is a difference in *what* you can spread: in an object spread, you can spread an object, but in an array spread, you must spread something that is iterable. I mention this just to highlight that although the syntax looks the same, they are different things. – trincot Jan 22 '20 at 21:05