Skip to content

Instantly share code, notes, and snippets.

@duduindo
Last active July 24, 2018 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duduindo/f347e2b5b69a6418ef5f228d0bbeb367 to your computer and use it in GitHub Desktop.
Save duduindo/f347e2b5b69a6418ef5f228d0bbeb367 to your computer and use it in GitHub Desktop.
Example of book Redux Book - Chapter 1 https://github.com/redux-book
<!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