A
A
Artur Galyaev2021-01-09 12:12:55
Vue.js
Artur Galyaev, 2021-01-09 12:12:55

How to optimize the management of items in a list in Vuex?

I receive categories of the form from the server

{
    id: 1,
    title: "category",
    products: [
        id: 1,
        title: "product",
        subproducts: [
            id: 1,
            title: "subproduct",    
        ]           
    ]       
}

A category can be products, a product can be subproducts
How do I manage this with Vuex? For example, adding a product locally would look like this:
ADD_PRODUCT(state, { categoryName, price, title, subproducts = [] }) {
            let categories = state.categories
            if (!categories) return
            let category = _.find(categories, { title: categoryName })
            if (!category) return
            category.products.push({ price, title, subproducts })
        },

Removing an offal like this:
REMOVE_SUBPRODUCT(state, { categoryId, productId, id }) {
            let categories = [...state.categories]
            let category = _.find(categories, { id: categoryId })
            if (!category) return
            let product = _.find(category.products, { id: productId })
            if (!product) return
            _.remove(product.subproducts, { id })
            state.categories = categories
        },

How can this be shortened and simplified?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question