I am currently working on a project that involves creating a dynamic product list similar to a shopping cart. I start by loading a series of products into an array of objects.
products = [
{
id: 1,
name: "Product1",
},
{
id: 2,
name: "Product2",
},
{
id: 3,
name: "Product",
},
];
To display the list of products using Svelte, I use the following code:
<div class="col-md-12 row grid">
{#each products as product}
<div class="card mt-2 g-col-3">
<div class="row">
<div class="col-md-8">
<div class="card-body">
<h5>{product.name}</h5>
<button
on:click={addProduct(product.id)}
class="btn btn-primary">Add Product
</button>
{ "0 products"}
</div>
</div>
</div>
</div>
{/each}
</div>
Utilizing the addProduct() function, I update the inventory array each time a user adds a new product along with the quantity of units for that product.
let inventory =[];
const addProduct = id =>{
let qty = 0;
if(inventory.find(element => element.id === id))
{
qty = inventory.find(element => element.id === id).qty
inventory=inventory.filter(element => element.id !== id)
inventory.push({id:id,qty:qty+1});
}
else{
inventory.push({id:id,qty:1});
}
}
A challenge I am facing is updating the product count dynamically as users add items to their cart within each product section where it currently says { "0 products"}. Any suggestions or solutions are greatly appreciated!
Thank you!