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,
});
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>
Top comments (3)
I'm stuck on this one. When I try to go to a category page, I expect to see a list of products from that category. Instead I get the following error showing on the screen instead: "500
Unsuccessful response (422: ) received
undefined"
Any help would be appreciated.
Hi ! I had the same problem the tutorial is not up to date now we pass an array of slug and no longer a single slug here :
Thanks for the update @matthieugll