Skip to curriculum
Jump to the editor

19.6. Store middlewares

Medium
Topics
20–35 min

A store's dispatch accepts only plain action objects and runs the reducer at once. Real apps want more around it: log every action, report errors, or dispatch a function that fetches data first and dispatches the result later. Middleware adds that without changing the store: each middleware wraps dispatch, sees every action on its way to the reducer, and may pass it on, change it, stop it or dispatch others.

Write two functions in middleware.js. applyMiddleware(store, ...middlewares) returns a new store whose dispatch runs the actions through the middlewares. thunk is a middleware that runs function actions. The store comes from createStore in store.js (given, read-only): its dispatch throws a TypeError for anything but a plain object with a string type.

Signature

JAVASCRIPT
function applyMiddleware(store, ...middlewares) // returns { getState, dispatch, subscribe }
function thunk({ dispatch, getState })           // returns next => action => result

A middleware is a function in three steps:

JAVASCRIPT
const middleware = ({ getState, dispatch }) => (next) => (action) => result;
  • getState() reads the store's current state; dispatch(action) starts a new action at the top of the chain.
  • next(action) hands the action to the next middleware; after the last one, next is the store's own dispatch.
  • What the action step returns is what the caller's dispatch returns.

Requirements

  1. applyMiddleware returns a new object with getState, dispatch and subscribe; the original store and its methods are not changed. getState and subscribe are the store's own.
  2. With no middlewares, the new dispatch behaves like the store's.
  3. Middlewares run in the order given: the first sees an action first, and the last one's next is the store's dispatch.
  4. The new dispatch returns exactly what the first middleware returns. A middleware that does not call next stops the action; one that passes a different action to next changes it.
  5. Each middleware's first two steps run once, inside applyMiddleware, not on every dispatch.
  6. The getState a middleware receives always reads the current state; its dispatch goes through the whole chain, from the first middleware.
  7. Calling that dispatch while applyMiddleware is still setting up the middlewares (in either of the first two steps) throws an Error.
  8. thunk: when the action is a function, it calls it with (dispatch, getState) and returns its result (a promise included), without calling next. Any other action goes to next, and thunk returns what next returned.
  9. Actions dispatched by a thunk, function actions included, go through the whole chain.
  10. Without thunk, a function action reaches the store and its TypeError.

Examples

JAVASCRIPT
const counter = (state = 0, action) => (action.type === "inc" ? state + 1 : state);
const logger = ({ getState }) => (next) => (action) => {
  console.log("before", getState());
  const result = next(action);
  console.log("after", getState());
  return result;
};

const store = applyMiddleware(createStore(counter), logger);
store.dispatch({ type: "inc" }); // "before 0", "after 1"; returns { type: "inc" }
JAVASCRIPT
const store = applyMiddleware(createStore(counter), thunk);
store.dispatch((dispatch, getState) => {
  dispatch({ type: "inc" });
  return getState();
}); // returns 1
JAVASCRIPT
const store = applyMiddleware(createStore(counter), logger, thunk);
store.dispatch(async (dispatch) => {
  await loadSomething();
  dispatch({ type: "inc" }); // the logger sees this action too
});
JAVASCRIPT
const eager = ({ dispatch }) => {
  dispatch({ type: "inc" });
  return (next) => (action) => next(action);
};
applyMiddleware(createStore(counter), eager); // Error: dispatch is not ready yet

Environment

  • Plain JavaScript in a browser page; the tests call the globals applyMiddleware and thunk from middleware.js, with stores from createStore in store.js. Do not change store.js.
  • The store's own behaviour (actions, listeners) is problem 19.5; here it is given.
  • Store enhancers and passing extra arguments to thunks are not part of this problem.

Hints

  1. If you have the list of "action steps" and the store's dispatch, which way do you fold them so that the first middleware ends up outermost?
  2. The dispatch handed to middlewares must exist before the chain does, yet call the chain once it is built. What can it call later that you assign afterwards?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…