Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
19.5. A Redux-style store
Medium
Topics
This question is in
19. Events, state and historyA 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
function createStore(reducer, preloadedState) // returns { getState, dispatch, subscribe }reducer(state, action): returns the next state. It must not changestateor calldispatch.preloadedState: the starting state, optional.getState(): returns the current state.dispatch(action): runs the reducer, then every listener. Returnsaction.subscribe(listener): adds a listener and returns anunsubscribe()function.
Requirements
createStorethrows aTypeErrorwhenreduceris not a function.- At creation the store dispatches
{ type: "@@store/INIT" }once, so the reducer receivespreloadedState(orundefined, and its default state applies). dispatch(action)replaces the state with exactly whatreducer(state, action)returned, and returns the sameactionobject.- An action must be a plain object (its prototype is
Object.prototypeornull) with a stringtype; anything else throws aTypeErrorbefore the reducer or any listener runs. - After every dispatch, even one that leaves the state unchanged, each listener runs once, with no arguments, in the order they subscribed.
subscribethrows aTypeErrorfor a non-function. Subscribing the same function twice makes two subscriptions; eachunsubscriberemoves only its own, and calling it again does nothing.- 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.
- Calling
dispatchfrom inside the reducer throws anError. - When the reducer throws, its error reaches the caller, the state stays as it was, and the store keeps working. A listener may dispatch.
- Each store has its own state.
Examples
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 anywayconst store = createStore((state, action) => state, { user: null });
store.getState(); // { user: null }
store.dispatch("inc"); // TypeError: not a plain object
store.dispatch({}); // TypeError: no string typeconst 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
createStorefromstore.js. - Middleware,
replaceReducerand 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
- Where can
stateand the list of listeners live so that the three methods share them, but two stores do not? - If
subscribeandunsubscribealways build a new array instead of changing the old one, what does a loop over the old array see? - 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…