I’m having trouble with
I have a repeater set up on a dynamic page to display 5 random items from my CMS dataset. I have a refresh button to refresh the content to display 5 new random results. This works once and shows the 5 new results, but then when clicked again it only reorders those 5 results instead of showing 5 new random ones. I think this may be due to the sort order on the dataset settings in the Editor that can’t be removed fully?
Working in
Wix Editor and Dev Mode
What I’m trying to do
When clicking refresh, it should display 5 new random results from the CMS data set and continue to do so.
What I’ve tried so far
I have the below code in Velo and have tried using the AI Code Assistant a number of times but it’s not working.
Thanks in advance!
Code
import wixData from ‘wix-data’;
async function loadRandomItems() {
try {
// Query the CMS collection to get all items
const result = await wixData.query(“ProteinMeals”).find();
const items = result.items;
// Shuffle the items array to randomize the order
const shuffledItems = items.sort(() => Math.random() - 0.5);
// Set the data property of the repeater to the shuffled items
$w("#repeater5").data = shuffledItems;
} catch (error) {
console.error("Error loading items:", error);
}
}
$w(“#repeater5”).onItemReady(($item, itemData, index) => {
// Example of setting data to elements inside the repeater
$item(“#repeatedImage”).src = itemData.image;
$item(“#repeatedText”).text = itemData.title;
});
$w(‘#button2’).onClick(() => {
const shuffleLimit = 5;
wixData.query(‘ProteinMeals’)
.limit(shuffleLimit)
.find()
.then((results) => {
if (results.items.length > 0) {
const shuffledItems = shuffleArray(results.items);
$w(‘#repeater5’).data = shuffledItems;
} else {
console.log(“No items found”);
}
})
.catch((error) => {
console.error(“Query failed”, error);
});
});
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i–) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}