Hi! I’m trying to populate a testimonial page with 3 cards that are chosen at random. I know that if you’re using a dataset in Wix builder, you can edit the settings so that it only displays a certain amount of items. How can I do this with code? So far I have this, to manually grab the dataset:
import wixData from 'wix-data';
$w.onReady(async function () {
$w("#repeater2").onItemReady(($item, itemData, index) => {
$item('#text234').text = "— " + itemData.reviewer; // adds name
$item('#text232').text = itemData.testimonial; // adds review
$item('#text234').link = itemData.link; // grab link
});
let results = await wixData.query("clubTestimonials").find();
let items = results.items;
console.log(items); // take a peek at the items
let shuffled = shuffleArray(items);
console.log(shuffled); // now see the shuffled array
$w('#repeater2').data = shuffled;
$w('#repeater2').expand();
});
function shuffleArray(array) {
for (let last = array.length - 1; last > 0; last--) {
const next = Math.floor(Math.random() * (last + 1));
[array[last], array[next]] = [array[next], array[last]];
return array;
}
}
But I cannot figure out how to only show 3 items in the array. I’ve been playing around with ‘if’, ‘then’, ‘while’, but I’m missing something. The whole dataset always loads, although it is shuffled each time.
An example, which I also tried moving in the shuffleArray function:
$w.onReady(async function () {
let fullCount = 0;
while (fullCount < 3) { //repeat until there are 3 items loaded
$w("#repeater2").onItemReady(($item, itemData, index) => {
$item('#text234').text = "— " + itemData.reviewer; // adds name
$item('#text232').text = itemData.testimonial; // adds review
$item('#text234').link = itemData.link; // grab link
});
let results = await wixData.query("clubTestimonials").find();
let items = results.items;
console.log(items); // take a peek at the items
let shuffled = shuffleArray(items);
console.log(shuffled); // now see the shuffled array
$w('#repeater2').data = shuffled;
$w('#repeater2').expand();
fullCount = fullCount + 1;
}
});
Please and thank you!