Building an E-Commerce Store - Browsing Products Chapter 10
Add the mutation to the initializeShop action:
initializeShop({commit}, products) {
commit('products', products);
commit('categories', products);
}
Viewing the app in the browser, you will be faced with a JavaScript error. This is because
some products do not contain a "type" for us to use to categorize them. Even with the
JavaScript error resolved, there are still a lot of categories that get listed out.
To help with the number of categories, and to group the uncategorized products, we
should make an "Miscellaneous" category. This will collate all the categories with two or
fewer products and group the products into their own group.
Creating a "miscellaneous" category
The first issue we need to negate is the nameless category. When looping through our
products, if no type is found, we should insert a category, so everything is categorized.
Create a new object in the categories method that contains the title and handle for a new
category. For the handle and variable call it other. Make the title a bit more user-friendly by
calling it Miscellaneous.
let categories = {},
other = {
title: 'Miscellaneous',
handle: 'other'
};
When looping through products, we can then check to see whether the type key exists, if
not, create an other category and append to it:
Object.keys(payload).forEach(key => {
let product = payload[key],
type = product.hasOwnProperty('type')? product.type : other;
if(!categories.hasOwnProperty(type.handle)) {
categories[type.handle] = {
title: type.title,
handle: type.handle,
products: []
}
}