0

As per my understanding this is how spread operator works:

x=[1,2,3];

y=[...x,4,5]; 

// this is same as y=[1,2,3,4,5]

const initialState={
  ingredients: [
    new Ingredient('Apples', 5),
    new Ingredient('Tomatoes', 10),
  ]
};
export function shoppingListReducer( state=initialState, action:ShoppingListActions.ShoppingListActions ) {
  switch(action.type) {
    case ShoppingListActions.ADD_INGREDIENT:
      return {
        ...state,
        ingredients:[...state.ingredients,action.payload ]
      }

    default:
      return state;
  }

Here in the above example what does

return {
  ...state,
  ingredients:[...state.ingredients,action.payload ]
}

evaluate to?

Payload is of type Ingredient :

export class Ingredient {
  constructor(public name: string, public amount: number) {}
}
SamuraiJack
  • 5,131
  • 15
  • 89
  • 195

2 Answers2

1

Basically you are trying to create an object with all the properties of state object and overriding its property ingredients with value as all the values in state.ingredients array along with action.payload. This might be done to separate the reference of the result object from state object.

var state = {
  "someprop" : "somevalue",
  "ingredients" : ["a", "b"]
};

var action = {
  "payload" : 4
};

var result = {
  ...state,
  ingredients:[...state.ingredients,action.payload ]
};
state.someprop = "somevalue1"; // does not alter result object
state.ingredients.push("c"); // does not alter result object
console.log(result);

Alternatively, to understand it better, you can break that into following

var result = {...state};
result.ingredients = [...state.ingredients, action.payload];

Note: In case there is a nested object in state or an object in array, they will still continue to share the same reference.

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

When used inside an object think of it as object.assign. the original state is added to object, then the next thing (ingredients), overwriting anything already there if necessary (ingredients), and so on down the line

Dude
  • 931
  • 6
  • 16
  • Why the downvote? This helps him conceptualize and make sense of whats happening in an easy manner without loading it down with overly technical answers. – Dude May 23 '19 at 18:07