How can I get the quantity of items in a cart?

Following


how can I get the quantity of an item to show up on the page? It shows how to make it show on a page with a table generator, but I want it to show on the page via a dynamic attribute.

Tried "cart.data[0].quantity" but I would need the 0 to match the item position in the dataset somehow.

Also tried "cart.data.where(`item_id`, item_id, '==')" where it would match the item id in the data store to the one on the page, but I don’t know how to then grab the quantity from the cart data.

First time using data store and assuming I’m just missing something simple.

Maybe explain in more details what are you trying to do on your page?

Basically, I just want to display how many of a selected item you have in your cart next to the add to cart button.

So on this step https://docs.wappler.io/t/creating-a-shopping-cart-with-the-data-store-component/17465#Add-products-to-the-shopping-cart

I want to pull the quantity of the item from the data store that matches the item in the repeat group and display it next to the add to cart button.

The .where formatter returns an array of items that match the specified condition

This can be checked on your browser developer console, where you could type something like:

dmx.parse("cart.data.where(`item_id`, item_id, '==')")
// Replace item_id with a number, I think it's the 2nd argument

Where it would return an array.

Assuming a single item is returned, you could access the first index of the array (0), and access the quantity property:

cart.data.where(`item_id`, item_id, '==')[0].quantity

Note I’ve never worked with carts before, I can’t help if this doesn’t work

I tried the command both ways but I got undefined.

I checked and the session storage is working with some test data.

Any ideas?

Since it didn’t work, we have to go a step before:

dmx.parse("cart.data")
dmx.parse("content.cart.data")

Check if any of the variables above exist

Or you’ll have to find it manually:

dmx.app.data
1 Like

The second one worked

For anyone in the future, this is what worked for me
cart.data.where(`item_id`, item_id, '==')[0].quantity

1 Like

Also, for the record, in the page you don’t need to use the prefix content. - this prefix is because the cart is located on a page and not on the main template, hence it’s prefixed with “content”

1 Like

Is the green button what you want to show on every page?

image

Just add {{Cart.data.sum(quantity)}} as in

{{Cart.data.sum(`quantity`)}} item<span dmx-show="(Cart.data.sum(`quantity`) > 1)">s</span>
1 Like

I wanted to display the quantity of just the one item and have it next to where you would add that item to the cart. Which I did end up getting working.

Thanks for the help though.

1 Like