Redux-style store with dispatch, subscribe, and getState
Many frontend apps keep shared state in a single store. Code never edits the state directly. It dispatches an action, a plain object that describes what happened, and a pure reducer function computes the next state from the current state and the action.
Implement createStore(reducer, preloadedState).
const store = createStore(reducer, preloadedState); // preloadedState is optional
store.getState(); // => current state
store.dispatch(action); // => action
store.subscribe(listener); // => unsubscribe function
TypeError if reducer is not a function.preloadedState (which may be undefined).{ type: '@@store/INIT' }, so the reducer can supply its default state. Listeners cannot exist yet, so none are called.TypeError unless action is an object (not null or an array) whose type property is a string. The reducer is not called and the state does not change.Error if called while the reducer is running (reducers must be pure).reducer(currentState, action), stores the result as the new state, then calls every listener in the order they subscribed, with no arguments. Listeners run on every dispatch, even if the state did not change.action.dispatch.TypeError if listener is not a function.unsubscribe function. Calling it more than once does nothing extra.subscribe is a separate subscription, even for the same function. Unsubscribing removes only that one.function cart(state = { items: [], total: 0 }, action) {
switch (action.type) {
case 'cart/add':
return {
items: [...state.items, action.item.name],
total: state.total + action.item.price,
};
case 'cart/clear':
return { items: [], total: 0 };
default:
return state;
}
}
const store = createStore(cart);
store.getState(); // => { items: [], total: 0 }
const unsubscribe = store.subscribe(() => {
console.log('Total:', store.getState().total);
});
store.dispatch({ type: 'cart/add', item: { name: 'Lamp', price: 40 } }); // logs "Total: 40"
store.dispatch({ type: 'cart/add', item: { name: 'Rug', price: 85 } }); // logs "Total: 125"
unsubscribe();
store.dispatch({ type: 'cart/clear' }); // logs nothing
store.getState(); // => { items: [], total: 0 }
store.dispatch('cart/clear'); // throws TypeError
createStore(cart, { items: ['Mug'], total: 12 }).getState(); // => { items: ['Mug'], total: 12 }