Building an E-Commerce Store - Browsing Products Chapter 10
Copy the code from the productPrice method on the ListProducts component and
place it within the loop. Update the second for loop so it loops
through product.variationProducts. Once this for loop has completed, we can add
the new properties to the product. Lastly, update the state with the new products object:
products(state, payload) {
let products = {};
Object.keys(payload).forEach(key => {
let product = payload[key];
let prices = [];
for(let variation of product.variationProducts) {
if(!prices.includes(variation.price)) {
prices.push(variation.price);
}
}
product.price = Math.min(...prices);
product.hasManyPrices = prices.length > 1;
products[key] = product;
});
state.products = products;
}
We can now update the productPrice method on the ListProducts component. Update
the function so it accepts the product, instead of variations. Remove the for loop from the
function, and update the variables so they use the price and hasManyPrices properties of
the product instead:
productPrice(product) {
let price = '$' + product.price;
if(product.hasManyPrices) {
price = 'From: ' + price;
}
return price;
}
Update the template so the product is passed to the function:
<p>Price {{ productPrice(product) }}</p>