Last active
July 24, 2018 12:09
-
-
Save duduindo/f347e2b5b69a6418ef5f228d0bbeb367 to your computer and use it in GitHub Desktop.
Example of book Redux Book - Chapter 1 https://github.com/redux-book
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Document</title> | |
<style> body { background: silver; } </style> | |
</head> | |
<body> | |
<main> | |
<h1 id="counter"></h1> | |
<button id="inc">+</button> | |
<button id="dec">-</button> | |
</main> | |
<script src="//unpkg.com/redux/dist/redux.js"></script> | |
<script> | |
// Our mutation (reducer) function creates | |
// a _new_ state based on the action passed | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'INC': | |
return Object.assign({}, state, { counter: state.counter + 1 }); | |
case 'DEC': | |
return Object.assign({}, state, { counter: state.counter - 1 }); | |
default: | |
return state; | |
} | |
} | |
const initialState = { | |
counter: 3 | |
}; | |
const store = Redux.createStore(reducer, initialState); | |
// Function to update view (this might be React or Angular in a real app) | |
function updateView() { | |
const { counter } = store.getState(); | |
document.querySelector('#counter').textContent = counter; | |
} | |
store.subscribe(updateView); | |
// Listen to click events | |
document.getElementById('inc').onclick = () => store.dispatch({ type: 'INC' }); | |
document.getElementById('dec').onclick = () => store.dispatch({ type: 'DEC' }); | |
// Update view for the first time | |
window.onload = () => updateView(); | |
//document.getElementById('inc').click(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment