Basics

Learn the basics of using Middleware API.

We can now take the previous example and encode the differences in the action’s payload. We initially had the following:

const fetchUser = id => dispatch =>
  axios.get(`http://api.ourserver.com/user/${id}`)
    .then(({ data: userData }) => dispatch(setUserData(userData)));

const fetchComments = id => dispatch =>
  axios.get(`http://api.ourserver.com/user/${id}/comments`)
    .then(({ data: commentsData }) => dispatch(setComments(commentsData)));

We can change it to the following:

const fetchUser = id => ({
  type: API,
  payload: {
    url: `http://api.ourserver.com/user/${id}`,
    onSuccess: setUserData
  }
});

const fetchComments = id => ({
  type: API,
  payload: {
    url: `http://api.ourserver.com/user/${id}/comments`,
    onSuccess: setComments
  }
});

The new action creators return plain JavaScript objects that are easy to test. Now we can move all the asynchronous code into our new API middleware:

const apiMiddleware = ({ dispatch }) => next => action => {
  next(action);

  if (action.type !== API) {
    return;
  }

  const { url, onSuccess } = action.payload;

  axios.get(url)
    .then(({ data }) => dispatch(onSuccess(data)));
};

It should immediately become clear that the middleware approach will give us a single place to encapsulate all the requirements of a server communication layer.

One of the biggest benefits is that all our action creators will return plain objects instead of async functions. This makes action creators much easier to create and test. With the API middleware approach, server communication is now declarativewe simply build an object describing the required network call.

Get hands-on with 1200+ tech skills courses.