Redux Counter Demo
Create a simple counter using React and vanilla javascript.
by LW
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js"></script>
<p>
Counter: <span id="counter">2</span>
</p>
<div class="button-group">
<button id="btn-increment">Increment</button>
<button id="btn-decrement">Decrement</button>
</div>
<div class="button-group">
<input type="text" id="value" placeholder="Input an Integer"/>
<button id="btn-add-value">Add Value</button>
</div>
<div class="button-group">
<button id="btn-reset">Reset</button>
</div>
CSS
.button-group {
margin: 1em 0;
}
input {
padding-left: 0.3em;
}
JavaScript
// Author: Harry Ganz
// Date: Aug. 4 2016
// HTML Elements
var counterSpan = document.getElementById('counter');
var btnIncrement = document.getElementById('btn-increment');
var btnDecrement = document.getElementById('btn-decrement');
var btnReset = document.getElementById('btn-reset');
var btnAddValue = document.getElementById('btn-add-value');
var valueInput = document.getElementById('value');
// Reducer Function
// Changes the current state of the counter based on the action
// @param currentState {number} The current count
// @param action {object} A javascript object with the state change.
// must have a property named 'type', usually a string, which indicates which
// modification to do, may have other properies holding data
// @return {number} The next state of the counter
function counter (currentState, action) {
var currentState = currentState || 0; // Initial State
var type = action.type
switch (type) {
case 'INCREMENT':
return currentState + 1;
case 'DECREMENT':
return currentState - 1;
case 'ADD_VALUE':
var value = parseInt(action.value);
// If is not a number return original state
if (isNaN(value)) {
return currentState;
} else {
return currentState + value;
}
case 'RESET':
return 0;
default:
return currentState; // Must return the next state
}
}
// The redux store takes dispatched actions,
// changes the state according to the reducer it is
// intitialized with
// then calls all the functions subscribed to it
var store = Redux.createStore(counter);
// Subscribe the counter to the current state of the store
// returns a function that unsubscribes callback
var unsubscribeCounter = store.subscribe(function () {
counterSpan.innerHTML = store.getState();
});
// Set up listeners for all the buttons that dispatch
// actions to the store
btnIncrement.addEventListener('click', function () {
store.dispatch({type:...