|
@@ -1,14 +1,29 @@
|
|
|
import ShoppingItem from 'types/shopping-cart';
|
|
import ShoppingItem from 'types/shopping-cart';
|
|
|
import { ActionTypes, ADD_TO_CART, REMOVE_FROM_CART } from './actions';
|
|
import { ActionTypes, ADD_TO_CART, REMOVE_FROM_CART } from './actions';
|
|
|
|
|
+import { DBRecipe } from 'src/types/recipes';
|
|
|
|
|
|
|
|
type ShoppingCartState = {
|
|
type ShoppingCartState = {
|
|
|
- cart: ShoppingItem[]
|
|
|
|
|
|
|
+ items: ShoppingItem[],
|
|
|
|
|
+ recipesId: string[],
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
const initialState: ShoppingCartState = {
|
|
const initialState: ShoppingCartState = {
|
|
|
- cart: []
|
|
|
|
|
|
|
+ items: [],
|
|
|
|
|
+ recipesId: []
|
|
|
};
|
|
};
|
|
|
|
|
|
|
|
|
|
+const getIngredients = (recipe: DBRecipe): ShoppingItem[] => {
|
|
|
|
|
+ return recipe.ingredients.reduce((ingredients, subRecipe) => {
|
|
|
|
|
+ return [
|
|
|
|
|
+ ...ingredients,
|
|
|
|
|
+ ...subRecipe.ingredients.map(ingredient => ({
|
|
|
|
|
+ ...ingredient,
|
|
|
|
|
+ recipeId: recipe._id
|
|
|
|
|
+ })),
|
|
|
|
|
+ ]
|
|
|
|
|
+ }, [] as ShoppingItem[])
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
const shoppingCartReducer = (
|
|
const shoppingCartReducer = (
|
|
|
state = initialState,
|
|
state = initialState,
|
|
|
action: ActionTypes
|
|
action: ActionTypes
|
|
@@ -16,16 +31,18 @@ const shoppingCartReducer = (
|
|
|
switch (action.type) {
|
|
switch (action.type) {
|
|
|
case ADD_TO_CART:
|
|
case ADD_TO_CART:
|
|
|
return {
|
|
return {
|
|
|
- cart: [
|
|
|
|
|
- ...state.cart,
|
|
|
|
|
- ...action.payload
|
|
|
|
|
- ]
|
|
|
|
|
|
|
+ items: [
|
|
|
|
|
+ ...state.items,
|
|
|
|
|
+ ...getIngredients(action.payload)
|
|
|
|
|
+ ],
|
|
|
|
|
+ recipesId: state.recipesId.concat([action.payload._id])
|
|
|
}
|
|
}
|
|
|
case REMOVE_FROM_CART:
|
|
case REMOVE_FROM_CART:
|
|
|
return {
|
|
return {
|
|
|
- cart: state.cart.filter(
|
|
|
|
|
|
|
+ items: state.items.filter(
|
|
|
item => item.recipeId !== action.payload
|
|
item => item.recipeId !== action.payload
|
|
|
- )
|
|
|
|
|
|
|
+ ),
|
|
|
|
|
+ recipesId: state.recipesId.filter(item => item !== action.payload)
|
|
|
}
|
|
}
|
|
|
default:
|
|
default:
|
|
|
return state
|
|
return state
|