Async Action Creators

Learn how to test async action creators.

Throughout this course, we have tried to discourage the use of asynchronous action creators and functions that have side effects and have used various libraries, like redux-thunk, to allow action creators to schedule async work and be non-idempotent. One of the main benefits is the ease of testing regular action creators offer.

For our example, we will create a simple async action creator that uses redux-thunk and the axios API to get recipe data from a server and dispatches the result with a SET_RECIPE action:

export const setRecipe = (id, data) => ({
  type: actions.SET_RECIPE,
  payload: { id, data }
});

export const fetchRecipe = id => dispatch => {
  return axios.get('recipe/' + id)
    .then(({ data }) => dispatch(setRecipe(id, data)))
};

With redux-thunk, our action creators can return a function instead of a plain JavaScript object. The thunk middleware will call such a function with the dispatch() and getState() methods as arguments. This allows the action creator to use the axios library to get data from the server and dispatch an action using dispatch().

Get hands-on with 1400+ tech skills courses.