Skip to content

Instantly share code, notes, and snippets.

@diogoca
Created January 7, 2018 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogoca/413c47adfc39626c7bcecc8351544e61 to your computer and use it in GitHub Desktop.
Save diogoca/413c47adfc39626c7bcecc8351544e61 to your computer and use it in GitHub Desktop.
Javascript with Redux Cart Example
<!DOCTYPE html>
<html>
<head>
<title>Redux basic example</title>
<script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
</head>
<body>
<h2>Itens</h2>
<button class="item">Apple</button>
<button class="item">Banana</button>
<div id="cart"></div>
<script>
// Reducer
function cart(state, action) {
if (typeof state === 'undefined') {
return [];
}
switch (action.type) {
case 'ADD':
state.push(action.payload);
return state;
case 'REMOVE':
state.splice(action.payload, 1);
return state;
}
}
// Store
var store = Redux.createStore(cart);
// Render
var cartEl = document.getElementById('cart');
function render() {
const itens = store.getState();
const total = itens.length;
var html = '<h2>Cart ' + total + ' itens</h2>';
html += itens.map((item, index) => {
return(
item + '<button onclick="removeFromCart(' + index + ')">Remove</button><br />'
);
}).join('');
cartEl.innerHTML = html;
}
render();
// Subscribe
store.subscribe(render);
// Actions
var bodyEl = document.body;
var itensEl = document.getElementsByClassName('item');
var itensArray = Array.from(itensEl);
itensArray.map((item) => {
item.addEventListener('click', () => {
store.dispatch({
type: 'ADD',
payload: item.textContent
});
});
});
function removeFromCart(index) {
store.dispatch({
type: 'REMOVE',
payload: index
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment