Skip to content

Commit 33c241e

Browse files
committed
Added action types UPDATE_INGREDIENT, DELETE_INGREDIENT in reducer, updated the service call with store dispatch in shopping-edit component
1 parent 90d9759 commit 33c241e

File tree

3 files changed

+34
-5
lines changed

3 files changed

+34
-5
lines changed

src/app/shopping-list/shopping-edit/shopping-edit.component.ts

+13-4
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,15 @@ export class ShoppingEditComponent implements OnInit, OnDestroy {
4343
const newIngredient = new Ingredient(value.name, value.amount);
4444

4545
if (this.editMode) {
46-
this.shoppingListService.updateIngredient(
47-
newIngredient,
48-
this.editedIngredientIndex
46+
// this.shoppingListService.updateIngredient(
47+
// newIngredient,
48+
// this.editedIngredientIndex
49+
// );
50+
this.store.dispatch(
51+
new ShoppingListActions.UpdateIngredient({
52+
ingredient: newIngredient,
53+
index: this.editedIngredientIndex,
54+
})
4955
);
5056
this.editMode = false;
5157
} else {
@@ -61,7 +67,10 @@ export class ShoppingEditComponent implements OnInit, OnDestroy {
6167
}
6268

6369
onDelete() {
64-
this.shoppingListService.deleteIngredient(this.editedIngredientIndex);
70+
// this.shoppingListService.deleteIngredient(this.editedIngredientIndex);
71+
this.store.dispatch(
72+
new ShoppingListActions.DeleteIngredient(this.editedIngredientIndex)
73+
);
6574
this.onClear();
6675
}
6776

src/app/shopping-list/store/shopping-list.actions.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ export class UpdateIngredient implements Action {
2323

2424
export class DeleteIngredient implements Action {
2525
readonly type = DELETE_INGREDIENT;
26-
constructor(public payload: { index: number }) {}
26+
constructor(public payload: number) {}
2727
}
2828

2929
export type ShoppingListActions =

src/app/shopping-list/store/shopping-list.reducer.ts

+20
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,26 @@ export function shoppingListReducer(
2828
...state,
2929
ingredients: [...state.ingredients, ...action.payload],
3030
};
31+
case ShoppingListActions.UPDATE_INGREDIENT:
32+
const ingToEdit = state.ingredients[action.payload.index];
33+
// ingToEdit.amount = action.payload.ingredient.amount; // not correct, since we should not overwrite the existing state
34+
const updatedIng = {
35+
...ingToEdit,
36+
...action.payload.ingredient,
37+
};
38+
const updatedIngs = [...state.ingredients];
39+
updatedIngs[action.payload.index] = updatedIng;
40+
return {
41+
...state,
42+
ingredients: updatedIngs,
43+
};
44+
case ShoppingListActions.DELETE_INGREDIENT:
45+
const ingsAfterDeletion = [...state.ingredients];
46+
ingsAfterDeletion.splice(action.payload, 1);
47+
return {
48+
...state,
49+
ingredients: ingsAfterDeletion,
50+
};
3151

3252
default:
3353
return state;

0 commit comments

Comments
 (0)