Product Page onReady does not run after wixLocation.to call

Hi All,

I am trying to create the repeatedProducts example posted here:

It fetches and displays the related products correctly the first time we go into the product page, but then, when we click on any of the related products in order to load the page of that product, the content and the URL changes fine, but the onReady function is not fired again for the new page. This means that the related products are still the same as they were before and they are not updated to reflect the related products for the newly clicked product.

I also tried to call again the loadRelatedProducts function when the wixLocation.to returned, but this is an asynchronous operation and the wixLocation.to method does not return a promise…

Could you please help?

My code is this:

import wixData from 'wix-data';
import wixLocation from 'wix-location';

$w.onReady(function () {
  console.log('Ready')
  $w("#relatedItems").collapse();
  loadRelatedProducts();
});

async function loadRelatedProducts() {
  console.log('In loadRelatedProducts')
 let product = await $w('#productPage').getProduct();
 console.log(product)
 let relatedProductResults = await Promise.all([
  relatedProductsByTable(product),
 //relatedProductsByPrice(product)
  ]);

console.log(relatedProductResults[0]);
 if (relatedProductResults[0].length > 0)
  showRelatedProducts(relatedProductResults[0]);
}

async function relatedProductsByTable(product) {
 let productId = product._id;

 // find related products by relation table
 let relatedByTable = await Promise.all([
  wixData.query('RelatedProducts')
  .eq('productA', productId)
  .ascending("order")
  .include('productB')
  .find()
 ]);

 let relatedProducts = [
  ...relatedByTable[0].items.map(_ => _.productB)
 ];
 return relatedProducts;
}

async function relatedProductsByPrice(product) {
 let productId = product._id;

 // find related products by price
 let relatedByPrice = await wixData.query('Stores/Products')
  .between('price', product.price * 0.8, product.price * 1.2)
  .ne('_id', productId)
  .find();
 return relatedByPrice.items;
}

function showRelatedProducts(relatedProducts){
 if(relatedProducts.length > 0) {
  relatedProducts.splice(3, relatedProducts.length);
 
  $w("#relatedItemsRepeater").data = relatedProducts;
 
 // $w("#productImage").onClick( (event) => {
 //   let $item = $w.at(event.context);
 //   $item("#productName").text = "Selected";
 // });
  $w('#relatedItemsRepeater').onItemReady(relatedItemReady);
  $w("#relatedItems").expand();
 }
 else {
  $w("#relatedItems").collapse();
 }
}

function relatedItemReady($item, product, index) {
  $item("#productImage").src = product.mainMedia;
  $item("#productName").text = product.name;
  $item("#productPrice").text = product.formattedPrice;

  console.log('Setting up onClick');
  $item("#productImage").onClick( (event) => {
    console.log(product.productPageUrl)
    wixLocation.to(product.productPageUrl)
  });
}