Building the Generic Action

Learn how to build the action discussed previously.

Potentially, we would like each of our data reducers to be able to handle a special UPDATE_DATA action and extract the relevant parts it needs:

const updateData = ({
  type: UPDATE_DATA,
  payload: {
    recipes: {
      63: {
        id: 63,
        name: 'French Toast',
        favorite: true,
        preparation: 'How to prepare...',
        ingredients: [5123, 729]
      }
    },
    ingredients: {
      5123: {
        id: 5123,
        name: 'Egg',
        quantity: 2
      },
      729: {
        id: 729,
        name: 'Milk',
        quantity: '2 cups'
      }
    }
  }
});

Using this approach, our recipe reducer’s support for UPDATE_DATA can be as simple as:

const recipesReducer = (state, action) => {
  switch (action.type) {
    case UPDATE_DATA:
      if (!('recipes' in action.payload)) return state;

      return Object.assign({}, state, {
        recipes: Object.assign({},
          state.recipes,
          action.payload.recipes
        )
      });
  }
};

Our reducer checks if the payload contains any recipes and merges the new data with the old recipes object, thus adding to or otherwise modifying it as needed.

Get hands-on with 1200+ tech skills courses.