Adding Ingredients

Learn how to add new ingredients in the application.

Similar to adding recipes, this step will require us to modify the reducer again to add support for adding ingredients:

const reducer = (state, action) => {
  switch (action.type) {
    case 'ADD_RECIPE':
      return Object.assign({}, state, {
        recipes: state.recipes.concat({ name: action.name })
      });

    case 'ADD_INGREDIENT':
      const newIngredient = {
        name: action.name,
        recipe: action.recipe,
        quantity: action.quantity
      };
      return Object.assign({}, state, {
        ingredients: state.ingredients.concat(newIngredient)
      });
   }

  return state;
};

Let’s test the new functionality by dispatching some actions from the browser console:

store.getState();

store.dispatch({ type: 'ADD_RECIPE', name: 'Pancakes' });

store.dispatch({
  type: 'ADD_INGREDIENT',
  recipe: 'Pancakes',
  name: 'Egg',
  quantity: 3
});

store.getState();

If you’ve followed the instructions correctly, you should be able to see the new recipe and ingredient in the state.

It’s hard to remember the properties that need to be passed in the action object while dispatching actions from the console to test the store. This is why we use the concept of action creatorsfunctions that create the action objects for us in Redux. For example:

const addIngredient = (recipe, name, quantity) => ({
  type: 'ADD_INGREDIENT', recipe, name, quantity
});

store.dispatch(addIngredient('Pancakes', 'Egg', 3));

This function both hides the structure of the action from the user and allows us to modify the action, setting default values for properties, performing the cleanup, trimming names, and so on.

Get hands-on with 1200+ tech skills courses.