B
B
bormor2018-08-23 11:07:25
JavaScript
bormor, 2018-08-23 11:07:25

Vuex for a directory with a basket - what is the best way to implement such a solution?

I took an example of a directory from the official documentation as a basis ( link
We have a repository with such a structure (conditionally)

products: [{}, {}, {}, ...]  // массив объектов с данными товаров
cartItems: [{id:1, quantity: 1}, ...]  // объесты со ссылками на id товара в products и количеством

We generate data for the cart in getters based on the products array
getters: 
  cartProducts: (state, getters, rootState) => {
    return state.items.map(({ id, quantity }) => {
      const product = rootState.products.all.find(product => product.id === id)
      return {
        title: product.title,
        price: product.price,
        quantity
      }
    })
  }
}

The question is how to get data for the basket of goods, if not all goods are stored in state.products, but only part of them (downloaded from the server for the current pagination page)?
The first ideas on this topic:
to get data for the basket - in actions, through Promise.all by id, pulling out data for each product?
but how then is it better to store and update this data (for example, by deleting a product or changing its quantity)?
Or is it better to get away from DRY and store full product data in cartItems?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-08-23
@bormor

get data for the cart - in actions, through Promise.all by id, pulling out data for each product?

In the sense - to store only the id in cartItems (well, the quantity and price), and each time the user enters the cart, pull up the rest of the data (name / manufacturer / warranty / ...)? First, what else is Promise.all - are you going to execute a separate request for each product? This is not how things are done - the id array should be transferred to the server, the request should be one. Secondly, it turns out that you have an id array in the storage, and the full data of the goods is locally stored in the basket component. In my opinion, it is somehow complicated, when manipulating cartItems data from the cart component, the latter will have to be manually kept up to date - watch on cartItems, filtering out remote items from the local array, copying the number of existing ones.
In short, when adding an item to the cart, I would simply copy the data from products into cartItems completely.

M
Mikhail Bobkov, 2018-08-23
@mike_bma

If there are no products you need in products, upload them.
You have an action that loads products on the page.
Make an action that will load products by id array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question