Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Spread Operator vs Map

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?

like image 886
Chris Kavanagh Avatar asked Jan 26 '23 09:01

Chris Kavanagh


1 Answers

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.

like image 56
Clarity Avatar answered Feb 02 '23 05:02

Clarity