Skip to curriculum
Jump to the editor

19.5. A Redux-style store

Medium
Topics
20–35 min

A shopping cart, a signed-in user and an open dialog are read and changed by many parts of a page. A store keeps such state in one place: the only way to change it is to dispatch an action, a plain object that says what happened, and a reducer function computes the next state from the current state and the action. Everything that cares subscribes and is told after each change.

Write createStore(reducer, preloadedState) in store.js. It returns a store with three methods: getState, dispatch and subscribe.

Signature

JAVASCRIPT
function createStore(reducer, preloadedState) // returns { getState, dispatch, subscribe }
  • reducer(state, action): returns the next state. It must not change state or call dispatch.
  • preloadedState: the starting state, optional.
  • getState(): returns the current state.
  • dispatch(action): runs the reducer, then every listener. Returns action.
  • subscribe(listener): adds a listener and returns an unsubscribe() function.

Requirements

  1. createStore throws a TypeError when reducer is not a function.
  2. At creation the store dispatches { type: "@@store/INIT" } once, so the reducer receives preloadedState (or undefined, and its default state applies).
  3. dispatch(action) replaces the state with exactly what reducer(state, action) returned, and returns the same action object.
  4. An action must be a plain object (its prototype is Object.prototype or null) with a string type; anything else throws a TypeError before the reducer or any listener runs.
  5. After every dispatch, even one that leaves the state unchanged, each listener runs once, with no arguments, in the order they subscribed.
  6. subscribe throws a TypeError for a non-function. Subscribing the same function twice makes two subscriptions; each unsubscribe removes only its own, and calling it again does nothing.
  7. The listeners of a dispatch are fixed when it starts notifying: a listener added during it runs from the next dispatch, and one removed during it still runs this time.
  8. Calling dispatch from inside the reducer throws an Error.
  9. When the reducer throws, its error reaches the caller, the state stays as it was, and the store keeps working. A listener may dispatch.
  10. Each store has its own state.

Examples

JAVASCRIPT
const counter = (state = 0, action) => (action.type === "inc" ? state + 1 : state);
const store = createStore(counter);

store.getState();                 // 0: the INIT dispatch applied the default
store.subscribe(() => console.log("now", store.getState()));
store.dispatch({ type: "inc" });  // logs "now 1", returns { type: "inc" }
store.dispatch({ type: "other" }); // logs "now 1": listeners run anyway
JAVASCRIPT
const store = createStore((state, action) => state, { user: null });
store.getState();          // { user: null }
store.dispatch("inc");     // TypeError: not a plain object
store.dispatch({});        // TypeError: no string type
JAVASCRIPT
const store = createStore(counter);
const unsubscribe = store.subscribe(() => {
  unsubscribe();
  store.subscribe(() => console.log("late"));
});
store.dispatch({ type: "inc" }); // nothing logged: "late" joins from the next dispatch
store.dispatch({ type: "inc" }); // "late"

Environment

  • Plain JavaScript in a browser page; the tests call the global createStore from store.js.
  • Middleware, replaceReducer and observable interop are not part of this problem. Middleware is problem 19.6.
  • The store does not copy or freeze the state: keeping it immutable is the reducer's job.

Hints

  1. Where can state and the list of listeners live so that the three methods share them, but two stores do not?
  2. If subscribe and unsubscribe always build a new array instead of changing the old one, what does a loop over the old array see?
  3. How do you make sure a "dispatching" flag is switched off even when the reducer throws?

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…