loading...
Cover image for 4. Create a products index page - Create a Commerce.js store with Svelte
Commerce.js

4. Create a products index page - Create a Commerce.js store with Svelte

notrab profile image Jamie Barton ・1 min read

Let's now create a dedicated page just for listing, and linking to product pages.



Inside the src/routes directory, create a the directory products, and file index.svelte.

This file will serve /products in the browser.

Just like we did before on the root index page, we can import the commerce.js instance, and fetch our products.

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

  export async function preload() {
    const { data: products } = await commerce.products.list();

    return {
      products,
    };
  }
</script>

<script>
  export let products;
</script>

<h1>Products</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

Since Sapper code splits your project per route, the special rel="prefetch" tells Sapper to start prefetching the data before navigating for the page.

Before we continue, let's add a link to the /products page on our root index page.

Above where we list products, add the following:

<h3><a href="/products">Products</a></h3>
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide