Using State

Learn how to use state in Redux-thunk.

Another feature we gain by using redux-thunk is access to the state when processing the action. This allows us to dispatch or suppress actions according to the current application state. For example, we can prevent actions from trying to add recipes with duplicate titles:

const addRecipe = (title) => (dispatch, getState) => {
  const trimmedTitle = trimTitle(title);

  // We don't allow duplicate titles
  if (getState().recipes.find(place => place.title == trimmedTitle)) {
    return; // No action is performed
  }

  dispatch({
    type: ADD_RECIPE,
    payload: { title: trimmedTitle }
  });
};

We can see two new concepts in this code. We used getState() to get access to the full application state and used a return statement that made our action creator emit no action at all.

Get hands-on with 1200+ tech skills courses.