Created
May 16, 2018 12:05
-
-
Save DamianMullins/8070e1673b1dc97dce0c67d8378a8d10 to your computer and use it in GitHub Desktop.
Vanilla Redux — Based on https://medium.com/front-end-hacking/vanilla-redux-e844628da6ff
This file contains 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> | |
<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