Skip to content

Instantly share code, notes, and snippets.

@sblondeau
Created February 26, 2020 22:01
Show Gist options
  • Save sblondeau/9c3fb1e9a3d250b729e44bac6d2ac5b7 to your computer and use it in GitHub Desktop.
Save sblondeau/9c3fb1e9a3d250b729e44bac6d2ac5b7 to your computer and use it in GitHub Desktop.
redux without React
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Counter Redux</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Redux CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>
</head>
<body>
<!-- Render the store -->
<p id="render-store"></p>
<button id="add">+1</button>
<button id="add10">+10</button>
<button id="remove">-</button>
<button id="remove10">-10</button>
<button id="reset">Reset</button>
<script src="main.js"></script>
</body>
</html>
// ACTIONS
const addAction = {
type: 'ADD',
};
const removeAction = {
type: 'REMOVE',
};
const remove10Action = {
type: 'REMOVE_TEN',
};
const add10Action = {
type: 'ADD_TEN',
};
const resetAction = {
type: 'RESET',
};
// REDUCER
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + 1;
case 'ADD_TEN':
return state + 10;
case 'REMOVE':
return state - 1;
case 'REMOVE_TEN':
return state - 10;
case 'RESET':
return 0;
default:
return state;
}
}
// STORE
const { createStore } = Redux;
const store = createStore(counterReducer);
// MAIN
const renderStore = document.getElementById('render-store');
const render = () => {
renderStore.innerHTML = store.getState();
}
store.subscribe(render);
render();
const add = document.getElementById('add');
add.addEventListener('click', () => {
store.dispatch(addAction)
});
const remove = document.getElementById('remove');
remove.addEventListener('click', () => {
store.dispatch(removeAction)
});
const add10 = document.getElementById('add10');
add10.addEventListener('click', () => {
store.dispatch(add10Action)
});
const remove10 = document.getElementById('remove10');
remove10.addEventListener('click', () => {
store.dispatch(remove10Action)
});
const reset = document.getElementById('reset');
reset
.addEventListener('click', () => {
store.dispatch(resetAction)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment