Product-Reviews section not loading

Hello.

I have recently created a review section for my website, and then I manually created a ‘related products area’, because when I was choosing the next product to look at from the Wix built-in ‘related products area’, the reviews that were shown were still the ones from the previous product.

I have figured that changing the product through the built-in ‘related products area’ doesn’t reload the page, that’s why the reviews don’t update. The reviews code assumes that the customer goes back to the product gallery and picks another product there => in this case, the page reloads and the reviews update.

Even after manually building the related products area and adding code which would technically reload the page, I still have the same problem.

Could anyone help me solve this issue? I believe that it is code related.

Thanks a lot!

//-------------Imports-------------//

import wixData from 'wix-data';
import wixWindow from 'wix-window';

//-------------Global Variables-------------//

// Current product.
let product;

//-------------Page Setup-------------//

$w.onReady(async function () {
 // Set the global product variable to the currently displayed product.
    product = await $w('#productPage1').getProduct();
 // Load the current product's reviews using the initReviews() function.
    initReviews();
 // Load the products that are related to the currently displayed product using the loadRelatedProducts() function.
    loadRelatedProducts(product);
});

// Loads the current product's reviews.
async function initReviews() {
 // Filter the "Reviews" dataset to contain only the reviews on the currently displayed product.
 await $w('#Reviews').setFilter(wixData.filter().eq('productId', product._id));
 // Show the reviews after the filter was set and applied on the dataset 
    showReviews();
 // Load the current product's statistics using the loadStatistics() function.
    loadStatistics();
}

// Load the current product's statistics.
async function loadStatistics() {
 // Get the statistics data based on the current product's ID.
 const stats = await wixData.get('review-stats', product._id);
 // If statistics data for the product was found:
 if (stats) {
 // Compute the product's average rating by dividing the total points by the number of ratings.
 let avgRating = (Math.round(stats.rating * 10 / stats.count) / 10);
 // Compute the percentage of reviewers that recommend the product.
 let percentRecommended = Math.round(stats.recommended / stats.count * 100);
 // Get the ratings element.
 let ratings = $w('#generalRatings');
 // Set the ratings element's average rating to the value calculated above. 
        ratings.rating = avgRating;
 // Set the ratings element's number of ratings to the count value from the statistics data.
        ratings.numRatings = stats.count;
 // Set the text for the recommended percentage element.
        $w('#recoPercent').text = `${percentRecommended} % would recommend`;
 // Show the ratings element.
        $w('#generalRatings').show();
 // If there is no statistics data for the product:
    } else {
 // Set the text for the recommended percentage element to reflect the fact that there are no reviews.
        $w('#recoPercent').text = 'There are no reviews yet';
    }
 // Show the recommended percentage element only after it is populated to avoid flickering.
    $w('#recoPercent').show();
}

//-------------Repeater Setup -------------//

// Set up each item in the reivews repeater as it is loaded.
export function reviewsRepeater_itemReady($w, itemData, index) {
 // If the reviewer recommends the item:
 if (itemData.recommends) {
 // Set the "recommend text.
        $w('#recommendation').text = 'I recommend this product.';
 // If the reviewer does not recommend the item:
    } else {
 // Set the "don't recomend" text.
        $w('#recommendation').text = "I don't recommend this product.";
    }

 // If a photo was uploaded for the review:
 if (itemData.photo) {
 // Set the image URL from the item data.
        $w('#reviewImage').src = itemData.photo;
 // Expand the image.
        $w('#reviewImage').expand();
    }

 // Set the ratings element's rating value.
    $w('#oneRating').rating = itemData.rating;

 // Get the date that the review was entered.
 let date = itemData._createdDate;
 // Format the date according to the date format settings on the user's computer.
    $w('#submissionTime').text = date.toLocaleString();
}

//-------------Data Setup -------------//

// Perform some setup when the dataset filter was completed.
export function showReviews() {
 // If at least one review has been submitted:
 if ($w('#Reviews').getTotalCount() > 0) {
 // Expand the strip that displays the reviews.
        $w('#reviewsStrip').expand();
 // If there are no reviews:
    } else {
 // Collapse the strip that displays the reviews.
        $w('#reviewsStrip').collapse(); //otherwise, hide it
    }
}

//-------------Event Handlers -------------//

// Set the action that occurs when a user clicks the "Write a Review" button.
export async function addReview_click(event, $w) {
 // Create an object containing the current product's ID to be sent to the review writing lightbox.
 const dataForLightbox = {
        productId: product._id
    };
 // Open the "Review Box" lightbox, send it the object created above, and wait for it to close.
 let result = await wixWindow.openLightbox('Review Box', dataForLightbox);
 // After the review lightbox is closed, refresh the reviews dataset so the new review appears on the page.
    $w('#Reviews').refresh();
 // Reload the current products statistics to reflect the new rating.
    loadStatistics();
 // Show a thank you message.
    $w('#thankYouMessage').show();
}

// Set the action that occurs when a user clicks the "Load More" text.
export function resultsPages_click(event, $w) {
 // Load additional reviews into the reviews repeater.
    $w('#Reviews').loadMore();
}

export function columnStrip3_click(event) {
 //Add your code for this event here: 
}

// Related products

//-------------Imports-------------//

import wixLocation from 'wix-location';

//-------------Page Setup-------------//

// Load the products that are related to the currently displayed product.
async function loadRelatedProducts(product1) {
 // Get the related product results using the relatedProductsByCollection() and relatedProductsByPrice() functions.
 let relatedProductResults = await Promise.all([
        relatedProductsByCollection(product1),
        relatedProductsByPrice(product1)
    ]);

 // If there are related products found in the "related-products" collection:    
 if (relatedProductResults[0].length > 0)
 // Show the related products from the collection.
        showRelatedProducts(relatedProductResults[0]);
 // If there are no related products found in the "related-products" collection: 
 else
 // Fallback to showing the related products by price.
        showRelatedProducts(relatedProductResults[1]);
}

// Get related products based on the relations set in the "related-products" collection.
async function relatedProductsByCollection(product2) {
 // Get the current product's ID.
 let productId = product2._id;

 // Find related products in the relationship collection by querying for related products in both relation directions.
 let relatedByTable = await Promise.all([
        wixData.query('related-products')
        .eq('productA', productId)
        .include('productB')
        .find(),
        wixData.query('related-products')
        .eq('productB', productId)
        .include('productA')
        .find()
    ]);

 // Merge related products found from both sides of the relationship collection.
 let relatedProducts = [
        ...relatedByTable[0].items.map(_ => _.productB),
        ...relatedByTable[1].items.map(_ => _.productA)
    ];

 //Return the related products found in the collection.
 return relatedProducts;
}

// Get related products based on the the product prices.
async function relatedProductsByPrice(product3) {
 // Get the current product's ID.
 let productId = product3._id;

 // Query the "Products" collection for product's whose price is within 20% of the current product's price.
 let relatedByPrice = await wixData.query('Stores/Products')
        .between('price', product3.price * 0.8, product3.price * 1.2)
        .ne('_id', productId)
        .find();
 // Return the related items extracted from the query results.
 return relatedByPrice.items;
}

// Show the related products on the page.
function showRelatedProducts(relatedProducts) {
 // If there are any related products:
 if (relatedProducts.length > 0) {
 // Remove all but the first four related items.
        relatedProducts.splice(4, relatedProducts.length);
 // Set the function that runs when the related items repeater data is loaded to be relatedItemReady().
        $w('#relatedItemsRepeater').onItemReady(relatedItemReady);
 // Set the related items repeater data to the first four related items.
        $w("#relatedItemsRepeater").data = relatedProducts;
 // Expand the related items repeater.
        $w("#relatedItems").expand();
    }
 // If there are no related products:
 else {
 // Collapse the related items repeater.
        $w("#relatedItems").collapse();
    }
}

// Set up the related items repeater as its data is loaded.
function relatedItemReady($item, product4) {
 // Populate the repeater elements from the item data.
    $item("#productImage").src = product4.mainMedia;
    $item("#productName").text = product4.name;
    $item("#productPrice").text = product4.formattedPrice;
 // Set the action that occurs when the image is clicked.
    $item('#container4').onClick(() => {
 // Navigate to the related product's product page.
        loadRelatedProducts(product4);
        wixLocation.to(product4.productPageUrl);
    });
}

1 Like