I'm building a simple shopping cart for a site and have been working on the add to cartaction. While I have ti working I feel there is probably a simple more elegant way of doing it.
This is the starting state:
start_state = {
inventory: [
{sku: "product_1", price: 600, name: "Product 1"},
{sku: "product_2", price: 800, name: "Product 2"}
],
cart: []
}
And this is the desired end state:
start_state = {
inventory: [
{sku: "product_1", price: 600, name: "Product 1"},
{sku: "product_2", price: 800, name: "Product 2"}
],
cart: [
{sku: "product_1", quantity: 2},
{sku: "product_2", quantity: 1}
]
}
And this is the function Im triggering to take it from the initial state to new final_state, the sku argument is the item from the state that is passed in when the action is called:
addToCart: function (sku) {
let currentCart = this.state.cart
let itemInCart = _.findIndex(currentCart, ['sku', sku])
let newItem = { sku: sku }
if (itemInCart !== -1) {
let newQuantity = currentCart[itemInCart].quantity
newItem.quantity = newQuantity + 1
} else {
newItem.quantity = 1
}
let filteredCart = _.filter(currentCart, (item) => { return item.sku !== sku })
let newCart = _.concat(filteredCart, newItem)
this.setState({cart: newCart})
},