Skip to content

Instantly share code, notes, and snippets.

@craigtaub
Last active August 22, 2017 20:01
Show Gist options
  • Save craigtaub/365d82c198b669572ae5d7785441d348 to your computer and use it in GitHub Desktop.
Save craigtaub/365d82c198b669572ae5d7785441d348 to your computer and use it in GitHub Desktop.
Vanilla Redux
// -------- declaration of Store, reducers, actions -------- --------
function createStore(reducers) {
let currentSubscribers = [];
const dispatch = (action) => {
const currentState = reducers[action.type](currentState, action);
for (let i = 0; i < currentSubscribers.length; i++) {
currentSubscribers[i](currentState);
}
}
const subscribe = (subscriber) => {
currentSubscribers = [...currentSubscribers, subscriber];
}
return {
dispatch, subscribe
}
}
const defaultState = {};
const reducers = {
['FIRST_ACTION']: (state = defaultState, action) => {
const newState = Object.assign({}, state, action);
return newState.payload;
}
}
const myFirstAction = (data) => ({
type: 'FIRST_ACTION',
payload: data
});
// -------- create component -------- -------- -------- --------
const MyComponent = (props) => {
console.log('prop:', props)
}
// -------- create store, subscribe + dispatch -------- -------- --------
const store = createStore(reducers);
store.subscribe(MyComponent)
store.dispatch(myFirstAction('some-data'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment