Skip to content

Instantly share code, notes, and snippets.

@gonzalovazquez
Created February 1, 2017 15:33
Show Gist options
  • Save gonzalovazquez/dc452c4ae82f2f717fa05d1ee8e68a97 to your computer and use it in GitHub Desktop.
Save gonzalovazquez/dc452c4ae82f2f717fa05d1ee8e68a97 to your computer and use it in GitHub Desktop.
Implementing Redux Store from Scratch
const counter = (state = 0,
action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
/* Store implementation from scratch */
const createStore = (reducer) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
};
};
dispatch({});
return { getState, dispatch, subscribe };
};
// Call createStore with
// counter as the reducer
// manages the state update
const store = createStore(counter);
/*
The store binds together the three
principles of Redux. It holds the
current application state object,
it lets you dispatch actions and
when you create it you need to specify
the reducer that tells how state
is updated with actions.
*/
// Retrives the current state of the
// redux store
console.log(store.getState());
// Lets you dispatch actions
// and change the state of your app
store.dispatch({type: 'INCREMENT'})
console.log(store.getState());
const render = () => {
document.body.innerText = store.getState();
}
/*
Lets you register a callback
The redux store will anytime
an action has been dispatched
so you can update the UI
to reflect the current application
state
*/
store.subscribe(render);
render();
// Dispatch event with click
document.addEventListener('click', () => {
store.dispatch({type: 'INCREMENT'});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment