DEV Community

Cover image for Implementing a Shopping Cart Functionality with Svelte
Dinesh kumar
Dinesh kumar

Posted on

Implementing a Shopping Cart Functionality with Svelte

Introduction

Svelte is a modern and powerful front-end framework for building reactive and performant web applications. One of the most common features in e-commerce applications is a shopping cart, which allows users to add, remove, and manage items they wish to purchase. In this article, we will walk through the process of implementing a shopping cart functionality using Svelte.

Prerequisites

To follow this tutorial, you need to have a basic understanding of HTML, CSS, and JavaScript, as well as a working knowledge of Svelte. Familiarity with Svelte stores is also recommended, as they will be utilized in this implementation.

Step 1: Setting up the project

First, create a new Svelte project using the degit command:

bash

npx degit sveltejs/template svelte-shopping-cart
cd svelte-shopping-cart
npm install
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating the product list

Create a new Svelte component called ProductList.svelte to display a list of available products:

html

<!-- src/components/ProductList.svelte -->
<script>
  export let products;
</script>

<ul>
  {#each products as product (product.id)}
    <li>
      <h3>{product.name}</h3>
      <p>Price: ${product.price.toFixed(2)}</p>
      <button on:click={() => $cart.addItem(product)}>Add to Cart</button>
    </li>
  {/each}
</ul>
Enter fullscreen mode Exit fullscreen mode

Step 3: Implementing the cart store

Create a new Svelte store called cartStore.js to manage the state of the shopping cart:

js

// src/stores/cartStore.js
import { writable } from 'svelte/store';

const initialState = {
  items: [],
  total: 0,
};

function createCart() {
  const { subscribe, set, update } = writable(initialState);

  return {
    subscribe,
    addItem: (product) =>
      update((state) => {
        const index = state.items.findIndex((item) => item.id === product.id);

        if (index !== -1) {
          state.items[index].quantity += 1;
        } else {
          state.items.push({ ...product, quantity: 1 });
        }

        state.total += product.price;
        return state;
      }),
    removeItem: (productId) =>
      update((state) => {
        const index = state.items.findIndex((item) => item.id === productId);

        if (index !== -1) {
          state.total -= state.items[index].price * state.items[index].quantity;
          state.items.splice(index, 1);
        }

        return state;
      }),
    clear: () => set(initialState),
  };
}

export const cart = createCart();
Enter fullscreen mode Exit fullscreen mode

Step 4: Creating the cart component

Create a new Svelte component called Cart.svelte to display the contents of the shopping cart:

html

<!-- src/components/Cart.svelte -->
<script>
  import { cart } from '../stores/cartStore.js';
</script>

<section>
  <h2>Shopping Cart</h2>
  <ul>
    {#each $cart.items as item (item.id)}
      <li>
        <span>{item.name} - {item.quantity} x ${item.price.toFixed(2)}</span>
        <button on:click={() => $cart.removeItem(item.id)}>Remove</button>
      </li>
    {/each}
  </ul>
  <p>Total: ${$cart.total.toFixed(2)}</p>
  <button on:click={$cart.clear}>Clear Cart</button>
</section>
Enter fullscreen mode Exit fullscreen mode

Step 5:

1 / 1

is completed

1 / 1

Great! Now that you've implemented a shopping cart functionality with Svelte, it's time to integrate the components into your main Svelte application.

Step 6: Integrating components into the main application

Update your App.svelte file to include the ProductList and Cart components:

html

<!-- src/App.svelte -->
<script>
  import ProductList from './components/ProductList.svelte';
  import Cart from './components/Cart.svelte';

  const products = [
    { id: 1, name: 'Product 1', price: 19.99 },
    { id: 2, name: 'Product 2', price: 29.99 },
    { id: 3, name: 'Product 3', price: 39.99 },
  ];
</script>

<main>
  <h1>My E-commerce App</h1>
  <ProductList {products} />
  <Cart />
</main>

<style>
  /* Add your custom styles here */
</style>
Enter fullscreen mode Exit fullscreen mode

Here, we've imported the ProductList and Cart components and included them in our main application. The products array contains sample product data for demonstration purposes.

Now, you can run the development server and see your shopping cart in action:

bash

npm run dev
Enter fullscreen mode Exit fullscreen mode

This will start the development server, and you can access your app at http://localhost:5000.

Conclusion

In this article, we demonstrated how to implement a shopping cart functionality using Svelte. We created a product list and a cart component, utilized Svelte stores to manage the cart state, and integrated the components into the main application. With this foundation, you can continue to expand the functionality and design of your e-commerce application.%

Top comments (0)