0

I want to create a simple webshop. On the page "products" a list of all offered products will be listed. When clicking into one product I want to show the ID and the name of the product. However, I am only able to display the ID of the product since I am getting it from the URl. Is there a method to also get the name out of the list by having the id?

Products:

<script>
  let products = [
    {
      id: 0,
      name: "Superbike",
    },
    {
      id: 1,
      name: "Ultrabike",
    },
  ];
</script>

<h1>Products</h1>
<ul>
  {#each products as product}
    <li><a href={"#/products/" + product.id}>{product.name}</a></li>
  {/each}
</ul>

Product Details:

<script>
  export let params = {};
  $: id = params.id;
  $: name = params.name;
</script>

<h1>Product Details</h1>
<p>Name: {name}</p>
<p>ID: {id}</p>
<p><a href="#/products/">Back to the list of products</a></p>

Products ProductDetails

I got the ID from the URl and wanted to also get the name by the ID. However, I don't know how I might be able to do that.

Janis
  • 1
  • 1

1 Answers1

0

Usually your products would be stored in some database and the details page makes a request to get the product details using the ID. If the user opens the product details page directly (e.g. from a shared link), there will be no "previous page", so you should not rely on passing data from it.

If you just want to set it up for testing, then extract the products list object into a separate module so it can be imported on the details page so you can search for the product via the ID.

H.B.
  • 166,899
  • 29
  • 327
  • 400