Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 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 }
    })
  }

Solution 3:

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.

Post a Comment for "Redux Spread Operator Vs Map"