Now we've individual pages for categories, it's now time to create the important pages for products.
We can do this by creating a new file with the name [permalink].svelte
inside the src/routes/products
directory.
The file is called [permalink]
because we'll be fetching Commerce.js products by their permalink
. You could alternatively use the product id
, but the permalink when customized is a bit more friendly.
Inside this file we'll make a call to commerce.products.retrieve()
and pass into the first argument the permalink
(from params
), and then in the 2nd argument, we'll tell it the type
is permalink
.
Once we've retrieved the product by permalink, we'll export the necessary variables, and return the product name, and formatted price to the page.
<script context="module">
import commerce from "../../lib/commerce.js";
export async function preload({ params }) {
const { permalink } = params;
const product = await commerce.products.retrieve(permalink, {
type: "permalink",
});
return {
product,
};
}
</script>
<script>
export let product;
</script>
<h1>{product.name}</h1>
<p>{product.price.formatted_with_symbol}</p>
🎉 Great!
You should see after running npm run dev
all of what we've built so far at http://localhost:3000.
We'll next explore using Commerce.js to add products to cart, and checkout.
Top comments (0)