// notes from https://egghead.io/lessons/react-redux-implementing-store-from-scratch
const createStore = (reducer) => {
let state;
let listeners = []; // keeps track of all the change listeners
const getState = () => state;
const dispatch = (action) => {
// calculate the new state by calling the reducer and update the state
state = reducer(state, action);
// call every change listener because an update has been made
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
// register a callback that will be called every time an action has been dispatched
listeners.push(listener);
// instead of adding a dedicated unsubscribe method,
// return a function that removes this listener from the listeners array
return () => {
listeners = listeners.filter(l => l!== listener);
}
};
// dispatch a dummy action just to populate the initial state
dispatch({});
return {getState, dispatch, subscribe};
}
Created
September 30, 2018 16:03
-
-
Save amysimmons/b335034952451d25209e7cf862022f47 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment