Skip to content

Instantly share code, notes, and snippets.

@msert29
Created October 2, 2017 09:53
Show Gist options
  • Save msert29/ed8312fa5ec00ce83504b53cee8184d1 to your computer and use it in GitHub Desktop.
Save msert29/ed8312fa5ec00ce83504b53cee8184d1 to your computer and use it in GitHub Desktop.
addItem(product){
// Get current list of products
let products = this.state.products
let idx = this.state.products.indexOf(product)
// Update the total price by quantity * price of the added product
let totalPrice = this.state.totalPrice + (product.price * product.quantity)
if (this.state.products.indexOf(product) !== -1) {
products[idx].quantity += 1;
} else {
products.push(product);
}
// Update the state
this.setState({
products: products,
totalPrice: totalPrice,
checkoutDisabled: this.totalPriceAboveMinimumOrder(totalPrice)
})
}
removeItem(product){
let idx = this.state.products.indexOf(product)
let products = this.state.products
let totalPrice = this.state.totalPrice - (product.price * product.quantity)
// Remove single item if multiple items added, else remove the whole item from cart
if (this.state.products[idx].quantity > 1 ){
products[idx].quantity -= 1
} else {
products.splice(idx, 1)
}
this.setState({
products: products,
totalPrice: totalPrice,
checkoutDisabled: this.totalPriceAboveMinimumOrder(totalPrice)}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment