Handling Typos and Duplicates

Learn how to avoid typos and duplicates.

We have been using strings like 'ADD_RECIPE' in our action creators and reducers but never bothered to verify that they match. In large applications, this often leads to very hard-to-debug errors, as a typo in the action creator will cause a reducer to ignore an action. Even worse, two developers might use the same string by mistake.

To fix these problems, we can utilize ES2015’s native const support, which guarantees that we cannot define the same constant twice in the same file. This will catch duplicate names at compile-time, even before our code reaches the browser.

Let’s create a new file, constants/actionTypes.js, which will hold all the action type constants in our application:

export const ADD_RECIPE = 'ADD_RECIPE';
export const ADD_INGREDIENT = 'ADD_INGREDIENT';

Now in our reducers and action creators, we will use the constants instead of the strings:

import { ADD_RECIPE } from '../constants/actionTypes';

const recipesReducer = (recipes = [], action) => {
  switch (action.type) {
    case ADD_RECIPE:
      ...

Go ahead and replace strings with action types in all your reducers and actions.

Get hands-on with 1200+ tech skills courses.