Skip to content

Instantly share code, notes, and snippets.

@stephenparish
Forked from MarcoWorms/mini-redux.js
Last active December 12, 2019 02:44
Show Gist options
  • Save stephenparish/606a262e60a8a075c762da01577351d8 to your computer and use it in GitHub Desktop.
Save stephenparish/606a262e60a8a075c762da01577351d8 to your computer and use it in GitHub Desktop.
Redux in a nutshell
function createStore (reducers) {
let state = reducers()
const subscribers = [];
const store = {
dispatch: (action) => {
state = reducers(state, action);
subscribers.forEach((subscriber) => subscriber());
},
getState: () => {
return state
},
subscribe: (subscriber) => {
subscribers.push(subscriber);
}
}
return store;
}
const reducers = (state = { counter: 0 }, action) => {
if (!action) { return state; }
switch (action.type) {
case 'INCREMENT':
return { counter: state.counter + 1 };
case 'DECREMENT':
return { counter: state.counter - 1 };
default:
return state;
}
}
const store = createStore(reducers);
store.subscribe(() =>
console.log(store.getState());
);
store.getState(); // => { counter: 0 }
store.dispatch({ type: 'INCREMENT' })
store.getState(); // => { counter: 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment