loading...
Cover image for 6. Create a individual category page - Create a Commerce.js store with Svelte
Commerce.js

6. Create a individual category page - Create a Commerce.js store with Svelte

notrab profile image Jamie Barton ・1 min read

Now that we've pages for all products and categories, it's time to create the individual pages for categories.



Using Sappers dynamic routes, we can create a new file inside src/routes/categories called [slug].svelte that works just like Nuxt and Next.js by passing this down as page params.

Inside src/routes/categories/[slug].svelte, we can use Commerce.js to:

  • Fetch the individual category by slug
  • Fetch all products that belong to this category

We'll perform the requests inside the exported async function preload, and return those to the page.

const category = await commerce.categories.retrieve(slug, {
  type: "slug",
});

const { data: products } = await commerce.products.list({
  category_slug: slug,
});
Enter fullscreen mode Exit fullscreen mode

It's important we export both of these inside the page <script /> tag so we can access it in the template.

Then on the page we will display the category name, followed by all products with links to the individual pages.

<script context="module">
  import commerce from "../../lib/commerce.js";

  export async function preload({ params }) {
    const { slug } = params;

    const category = await commerce.categories.retrieve(slug, {
      type: "slug",
    });
    const { data: products } = await commerce.products.list({
      category_slug: slug,
    });

    return {
      category,
      products,
    };
  }
</script>

<script>
  export let category;
  export let products;
</script>

<h1>{category.name}</h1>

<ul>
  {#each products as product}
    <li>
      <a rel="prefetch" href="products/{product.permalink}">{product.name}</a>
    </li>
  {/each}
</ul>
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide