I’ve been working to implement the code found on this tutorial to create a related products section on my site’s product pages. I’ve made a few tweaks and changes because I do not need the secondary function pulling items of similar price if related items are not defined in the database table - I only want related products to show if they are defined in the table. Otherwise, I want the whole section to collapse.
The issue I’m running into is that while I’ve accomplished my goal of only showing the defined related products on the defined product page, the strip and repeater template are still showing up on pages that don’t have related products defined.
Any help is appreciated! I’ve copied my code below so you can take a look:
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([
relatedProductsByTable(product)
]);
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)
.include(‘productB’)
.find(),
]);
let relatedProducts = [
…relatedByTable[0].items.map(_ => _.productB)
];
return relatedProducts;
}
function showRelatedProducts(relatedProducts) {
if (relatedProducts.length > 0) {
relatedProducts.splice(20, relatedProducts.length);
$w(‘#relatedItemsRepeater’).onItemReady(relatedItemReady);
$w(“#relatedItemsRepeater”).data = relatedProducts;
$w(“#relatedProducts”).expand();
} else {
$w(“#relatedProducts”).collapse();
}
}
function relatedItemReady($w, product) {
$w(“#productImage”).src = product.mainMedia;
$w(“#productName”).text = product.name;
$w(‘#productImage’).onClick(() => {
wixLocation.to(product.productPageUrl);
});
}