- Add products.
- Show products in the cart.
- Update product quantity in the cart.
It seems really simple but I had a hard time doing it. But when I tried the same in Svelte, it felt like a breeze.
Check out this REPL: Svelte shopping cart
I will show you - with snippets - how I did it.
Create an array of products. Each products usually will have details like id, name, image, price etc.
Create an empty array called cart. The idea is to add items from products to the cart whenever Add to cart is clicked.
Let’s show these prodcuts along with a button.
That should display it in a grid with add a non-functional button.
Now, let’s add a function
addToCart() to buttons. We will have to send the prodcut along with this function as shown below.
We can create this function to receive the sent product and push it to the cart.
Now, in Svelte this will not be reactive because there is not assignment used. We can rewite this usig spread operator as shown below.
The problem with this is that when you add the same item multiple times, it keeps on adding to the cart array. We don’t want that. We would like only the quantity of the cart item to increase if it is already present.
When Add to cart is clicked, we can go through all the cart items to see whether the item just added is already in the cart, if so then we increment the quantity as shown below.
We can display the cart a better way as shown below.
We can also add buttons besides quantity to add or remove the items added to the cart. This function is pretty much same as the
addToCart() function that we already discussed.
Let’s add those buttons with functions sending product as parameter.
We can define those functions to add or remove items from the cart array as shown here.
That should take care of the button functions in the cart.
Now this is almost complete. But I have used a single component. In the next article I will be doing the following,
- Use components to simplify the app.
- Use writable store to maintain state across the app.
- Use session store to persist the cart even on browser refresh.
Watch the video here: