19.6. Store middlewares
Topics
This question is in
19. Events, state and historyA 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
function applyMiddleware(store, ...middlewares) // returns { getState, dispatch, subscribe }
function thunk({ dispatch, getState }) // returns next => action => resultA middleware is a function in three steps:
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,nextis the store's owndispatch.- What the action step returns is what the caller's
dispatchreturns.
Requirements
applyMiddlewarereturns a new object withgetState,dispatchandsubscribe; the original store and its methods are not changed.getStateandsubscribeare the store's own.- With no middlewares, the new
dispatchbehaves like the store's. - Middlewares run in the order given: the first sees an action first, and the last one's
nextis the store'sdispatch. - The new
dispatchreturns exactly what the first middleware returns. A middleware that does not callnextstops the action; one that passes a different action tonextchanges it. - Each middleware's first two steps run once, inside
applyMiddleware, not on every dispatch. - The
getStatea middleware receives always reads the current state; itsdispatchgoes through the whole chain, from the first middleware. - Calling that
dispatchwhileapplyMiddlewareis still setting up the middlewares (in either of the first two steps) throws anError. thunk: when the action is a function, it calls it with(dispatch, getState)and returns its result (a promise included), without callingnext. Any other action goes tonext, andthunkreturns whatnextreturned.- Actions dispatched by a thunk, function actions included, go through the whole chain.
- Without
thunk, a function action reaches the store and itsTypeError.
Examples
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" }const store = applyMiddleware(createStore(counter), thunk);
store.dispatch((dispatch, getState) => {
dispatch({ type: "inc" });
return getState();
}); // returns 1const store = applyMiddleware(createStore(counter), logger, thunk);
store.dispatch(async (dispatch) => {
await loadSomething();
dispatch({ type: "inc" }); // the logger sees this action too
});const eager = ({ dispatch }) => {
dispatch({ type: "inc" });
return (next) => (action) => next(action);
};
applyMiddleware(createStore(counter), eager); // Error: dispatch is not ready yetEnvironment
- Plain JavaScript in a browser page; the tests call the globals
applyMiddlewareandthunkfrommiddleware.js, with stores fromcreateStoreinstore.js. Do not changestore.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
- 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? - The
dispatchhanded 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