Redux Example
Example to use Redux
by sarbjit87
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.5/redux.min.js"></script>
<pre id="output">Output </pre>
JavaScript
// Function to print output
function out() {
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
// Initial State for the store
const initialState = {
count: 0
}
// Reducer to handle actions and update store
const reducer = (state, action) => {
if (typeof state === 'undefined') {
return initialState
}
switch (action.type) {
case 'ADD':
return {
...state,
count: state.count + action.value
}
case 'REMOVE':
return {
...state,
count: state.count - action.value
}
default:
return state
}
}
// Create a store
const store = Redux.createStore(reducer);
// Subscriptions
store.subscribe(() => {
out("Automatic Message from subscription : " + store.getState().count)
})
// Display current state of the store
out(store.getState().count)
// Dispatch an action and display results
store.dispatch({
type: 'ADD',
value: 5
})
out("Explicit print call : " + store.getState().count)
store.dispatch({
type: 'REMOVE',
value: 2
})
out("Explicit print call : " + store.getState().count)