Skip to content

Instantly share code, notes, and snippets.

@DamianMullins
Created May 16, 2018 12:05
Show Gist options
  • Save DamianMullins/8070e1673b1dc97dce0c67d8378a8d10 to your computer and use it in GitHub Desktop.
Save DamianMullins/8070e1673b1dc97dce0c67d8378a8d10 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Vanilla Redux</title>
<script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
</head>
<body>
<p>
Counter:
<span data-js-value>0</span> times
<button type="button" data-js-increment>+</button>
<button type="button" data-js-decrement>-</button>
<button type="button" data-js-incrementIfOdd>Increment if odd</button>
<button type="button" data-js-incrementAsync>Increment async</button>
</p>
<script>
const valueEl = document.querySelector('[data-js-value]');
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
const store = Redux.createStore(counter)
const render = () => {
valueEl.innerHTML = store.getState().toString();
}
render();
store.subscribe(render);
document.querySelector('[data-js-increment]')
.addEventListener('click', () => {
console.log('increment');
store.dispatch({ type: 'INCREMENT' });
});
document.querySelector('[data-js-decrement]')
.addEventListener('click', () => {
console.log('decrement');
store.dispatch({ type: 'DECREMENT' });
});
document.querySelector('[data-js-incrementIfOdd]')
.addEventListener('click', () => {
console.log('incrementIfOdd');
if (store.getState() % 2 !== 0) {
store.dispatch({ type: 'INCREMENT' });
}
});
document.querySelector('[data-js-incrementAsync]')
.addEventListener('click', () => {
console.log('incrementAsync');
setTimeout(() => {
store.dispatch({ type: 'INCREMENT'});
}, 1000);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment