Building an E-Commerce Store - Adding a Checkout Chapter 11
We can now proceed with adding the products to the basket array. The first step is to add
the product object with the mentioned properties. As it's an array, we can use the push()
function to add the object.
Next, add an object to the array, using the item and its properties to build the object. With
access to the ProductPage component, we can construct the variant title as it appears in
the select box, using the variantTitle method. Set the quantity to 1 by default:
addToBasket(state, item) {
state.basket.push({
sku: item.variation.sku,
title: item.product.title,
handle: item.slug,
image: item.image,
variationTitle: item.variantTitle(item.variation),
variation: item.variation,
quantity: 1
});
}
This now adds the product to the basket array. An issue appears, however, when you add
two of the same item to the basket. Rather than increasing the quantity, it simply adds a
second product.
This can be remedied by checking if the sku exists within the array already. If it does, we
can increment the quantity on that item, if not we can add a new item to the basket array.
The sku is unique for each variation of each product. Alternatively, we could use the
barcode property.
Using the native find JavaScript function, we can identify any products that have an SKU
matching that of the one being passed in:
addToBasket(state, item) {
let product = state.basket.find(p => {
if(p.sku == item.variation.sku) {
}
});
state.basket.push({
sku: item.variation.sku,
title: item.product.title,
handle: item.slug,
image: item.image,