Last active
February 1, 2017 15:33
-
-
Save gonzalovazquez/e0501fe427ec59246d1eddbf9633eb63 to your computer and use it in GitHub Desktop.
A simple Redux implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
HTML Requires: | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.js"></script> | |
*/ | |
const counter = (state = 0, | |
action) => { | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1; | |
case 'DECREMENT': | |
return state - 1; | |
default: | |
return state; | |
} | |
} | |
const { createStore } = Redux; | |
// 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