Skip to content

Instantly share code, notes, and snippets.

@Nocktiss
Created June 3, 2019 12:53
Show Gist options
  • Save Nocktiss/db4e34beb0429482e89d95c13e3e73ca to your computer and use it in GitHub Desktop.
Save Nocktiss/db4e34beb0429482e89d95c13e3e73ca to your computer and use it in GitHub Desktop.
Javascript Redux
<!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">+</button>
<button id="remove">-</button>
<button id="add10">+10</button>
<button id="remove10">-10</button>
<script src="main.js"></script>
</body>
</html>
const addAction = {
type: 'ADD',
};
const removeAction = {
type: 'REMOVE',
};
const add10 = {
type: 'ADD10',
};
const remove10 = {
type: 'REMOVE10'
};
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + 1;
case 'REMOVE':
return state - 1;
case 'ADD10':
return state + 10;
case 'REMOVE10':
return state - 10;
default:
return state;
}
}
const { createStore } = Redux;
const store = createStore(counterReducer);
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 addsup = document.getElementById('add10');
addsup.addEventListener('click', () => {
store.dispatch(add10)
});
const removesup = document.getElementById('remove10');
removesup.addEventListener('click', () => {
store.dispatch(remove10)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment