This is the code:
import wixData from ‘wix-data’;
import wixLocation from ‘wix-location’;
$w.onReady( function () {
loadRelatedProducts();
});
async function loadRelatedProducts() {
let product = await $w(‘#productPage’).getProduct();
let relatedProductResults = await Promise.all([
relatedProductsByCollection(product),
]);
if (relatedProductResults[0].length > 0)
// Show the related products from the collection.
showRelatedProducts(relatedProductResults[0]);
}
async function relatedProductsByCollection(product) {
let productId = product._id;
let relatedByTable = await Promise.all([
wixData.query(‘relatedProducts’)
.eq(‘productA’, productId)
.include(‘productB’)
.find(),
]);
let relatedProducts = [
…relatedByTable[0].items.map(_ => _.productB),
];
return relatedProducts;
}
function showRelatedProducts(relatedProducts){
if (relatedProducts.length > 0){
relatedProducts.splice(4, relatedProducts.length);
$w('#relatedItemsRepeater').onItemReady(relatedItemReady);
$w("#relatedItemsRepeater").data = relatedProducts;
$w("#relatedItems").expand();
}
// If there are no related products:
else {
// Collapse the related items repeater.
$w(“#relatedItems”).collapse();
}
}
function relatedItemReady($w, product){
$w("#productImage").src = product.mainMedia;
$w("#productName").text = product.name;
$w("#productPrice").text = product.formattedPrice;
$w('#productImage').onClick(() => {
wixLocation.to(product.productPageUrl);
});
}