I've followed Wix's guide to create a Related Products area at the bottom of their dynamic product page.
It mostly works as you'd expect. The problem comes when you click on one of the related products and see that the related products list doesn't change to reflect the currently loaded product.
The only way to get the related products list to change is by refreshing the page.
Is there possibly a simple fix for this? Below is their code:
import wixData from 'wix-data';
import wixLocation from 'wix-location';
$w.onReady(function () {
loadRelatedProducts();
});
async function loadRelatedProducts() {
let product = await $w('#productPage1').getProduct();
let relatedProductResults = await Promise.all([
relatedProductsByTable(product),
relatedProductsByPrice(product)
]);
if (relatedProductResults[0].length > 0)
showRelatedProducts(relatedProductResults[0]);
else
showRelatedProducts(relatedProductResults[1]);
}
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(),
wixData.query('RelatedProducts')
.eq('productB', productId)
.include('productA')
.find()
]);
let relatedProducts = [
...relatedByTable[0].items.map(_ => _.productB),
...relatedByTable[1].items.map(_ => _.productA)
];
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(4, relatedProducts.length);
$w('#relatedItemsRepeater').onItemReady(relatedItemReady);
$w("#relatedItemsRepeater").data = relatedProducts;
$w("#relatedItems").expand();
}
else {
$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);
});
}
I suspect the issue is in this all being triggered by the .onReady() event. Unfortunately, I'm not sure how to also make this re-run on another trigger like when the related item itself is clicked.
The page itself does not reload when you click one of the related products. Instead, I believe they are simply rewriting the URL and then updating then re-fetching data from the database.