Other Action Types

Learn to use other action types in Redux.

Developers are usually taught that actions in Redux can only be objects, and that they must contain the type property. You will notice Error objects, functions, and promises being passed to dispatch().

The underlying rule is simple: our root reducer requires an object as an action, but our middleware has no such limits and is free to handle any type of data passed to dispatch().

Try running dispatch(null). You should get an error from Redux similar to:

store.dispatch(null);
> Uncaught TypeError: Cannot read property 'type' of null(...)

To add support for null, we can create our own nullMiddleware:

const nullMiddleware = () => next => action => {
  next(action !== null ? action : { type: 'UNKNOWN' });
};

This middleware catches any attempt to send null instead of the action object and dispatch a fake { type: 'UNKNOWN' } instead. While this middleware has no practical value, it should be apparent how we can use the middleware’s power to change actions to support any input type.

The famous redux-thunk middleware code is as follows:

const thunkMiddleware = ({ dispatch, getState }) => next => action => {
  if (typeof action === 'function') {
    return action(dispatch, getState);
  }

  return next(action);
};

It checks if the action passed is a function and not a regular object, and if it is, it calls it, passing dispatch() and getState(). Other helper middleware use a similar approach that accepts promises which dispatch a regular action once a promise is resolved, uses Error objects to report errors, and uses arrays to execute a list of actions provided in parallel or sequentially, and more.

Get hands-on with 1400+ tech skills courses.