Random Sort a Gallery Not Working

I am trying to randomly sort a slider gallery on page load. The pro gallery is connected to #datasetCourses, with about 50 images of which 10 are visible at a time.

When I run this code the gallery appears on page load but not sorted randomly.
If I set the same code to run when I click a button, it works perfectly.

$w.onReady(function () {
    $w("#datasetCourses").onReady(()=> {
        let unsorted = $w("#gallery3").items;
        let randomSort = shuffle(unsorted);
        $w("#gallery3").items = randomSort;
    });
}};


function shuffle(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

I’ve tried a few things:
-using async…await or .then with the shuffle function
-adjusting the dataset settings in the Editor (turning on/off “Fetch after the page loads”).
-refresh() dataset.

Hi, @Baksheesh !!

I think it would work more easily if we stopped using the dataset and instead used wix-data to fetch the items, sort them, and set them directly to the gallery. The current method might not be working properly due to a timing issue, where the randomized values could be getting overwritten by the original ones. For now, let’s try delaying the timing with setTimeout() and see if that helps. :innocent:

$w.onReady(function () {
    $w("#datasetCourses").onReady(()=> {
        setTimeout(()=>{
            let unsorted = $w("#gallery3").items;
            let randomSort = shuffle(unsorted);
            $w("#gallery3").items = randomSort;
        },3000);
    });
}};

If this works, we might be able to explain why it succeeds when triggered by a click action, which could help us identify points for improvement.

1 Like

Thanks. I also suspected a timing issue, but thought the dataset onReady() would have minimized it. Experimented and the shuffle does appear to work on page load if the delay is set > 1500.

Understood. :innocent: That means the issue has become clear. However, since there’s no guarantee that simply waiting 1500ms will always work, it would be unstable and not a proper solution in its current form.

I believe the root cause of the current issue is that the dataset is connected to the gallery. So, if you really want to use a dataset for the implementation, it might be a good idea to disconnect the two and let them operate independently.
The problem is that because they are connected, the non-randomized data gets loaded at least once.

In situations like this, using a dataset tends to make things a bit more complicated. I think it would be much simpler and easier to understand if we just used the wix-data API directly to fetch the data, randomize it, and then feed it to the gallery.

It might be helpful to refer to previous examples like the following. :upside_down_face:

All good advice, and a few things I hadn’t considered. Thanks for making sense of it.