Skip to content

Instantly share code, notes, and snippets.

@alexlafroscia
Created March 13, 2017 23:44
Show Gist options
  • Save alexlafroscia/af0f65a39e9add45ff19acb0988a9df7 to your computer and use it in GitHub Desktop.
Save alexlafroscia/af0f65a39e9add45ff19acb0988a9df7 to your computer and use it in GitHub Desktop.
redux cart
import Ember from 'ember';
import connect from 'ember-redux/components/connect';
const stateToComputed = (state) => {
return {
numberOfTypes: state.cart.length,
totalCartCount: state.cart.reduce((totalCount, product) => totalCount += product.count, 0),
cartItems: state.cart
};
};
const dispatchToActions = (dispatch) => {
return {
add: (product) => dispatch({ type: 'ADD_PRODUCT', product })
};
};
const ApplicationController = Ember.Controller.extend({
appName: 'Ember Twiddle'
})
export default connect(stateToComputed, dispatchToActions)(ApplicationController);
function addProduct(cart, product) {
const { type } = product;
const existingProductType = cart.find((product) => product.type === type);
if (existingProductType) {
existingProductType.count += 1;
} else {
cart.push({ type, count: 1 });
}
return cart;
}
export default function cart(state, { type, product }) {
switch (type) {
case 'ADD_PRODUCT':
return addProduct(state, product);
default:
return [];
};
};
import cart from './cart';
export default {
cart
};
<h1>Cart Items</h1>
<br>
{{numberOfTypes}} types of items
<br>
{{totalCartCount}} total number of items
{{#each cartItems as |item|}}
{{item.type}}: {{item.count}}
<br>
{{/each}}
<br>
<button {{action 'add' (hash type='foo')}}>
Add Foo to Cart
</button>
<button {{action 'add' (hash type='bar')}}>
Add Bar to Cart
</button>
{
"version": "0.11.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.11.0",
"ember-data": "2.11.0",
"ember-template-compiler": "2.11.0",
"ember-testing": "2.11.0"
},
"addons": {
"ember-redux": "2.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment