Item indices not being updated on repeater

I’m trying to create a filteration system such that when we click on the “read more” button and come back to the filteration system, the order of the filtered data remains the same.

However, when I return to the filteration system page, the order is randomized.

export async function allCoaches() {
    $w("#text35").hide();

    console.log("beginning");
    console.log(storedItems);

    if (storedItems == null) {
        queryResults = await wixData.query("Team2")
            .find();

        // Shuffle the items
        randomize(queryResults);

        // Sort the items in descending order
        queryResults.items.sort((a, b) => b.age - a.age);

        // Generate unique IDs and store items
        items = queryResults.items.map(item => ({
            ...item,
            _id: generateUniqueID()
        }));
    } else {
        // If items are already stored, use them directly
        items = storedItems;

        console.log("middle");
        console.log(storedItems);
    }

    // Ensure that all items have valid _id values
    items = items.map(item => ({
        ...item,
        _id: item._id || generateUniqueID()
    }));

    // Update indices for items
    items.forEach((item, index) => {
        item.index = index;
    });

    // Update repeater data
    $w("#teamRepeater").data = items.slice(0, itemsPerPage);

    if (items.length > itemsPerPage) {
        $w('#button5').expand();
    }

    $w('#button5').onClick((event) => {
        currentPage++;
        const startIndex = (currentPage - 1) * itemsPerPage;

        // Fetch the next page of items from the filtered set
        const nextPageItems = items.slice(startIndex, startIndex + itemsPerPage);

        // Update repeater data with the next page of filtered items
        $w("#teamRepeater").data = $w("#teamRepeater").data.concat(nextPageItems);

        if (startIndex + itemsPerPage >= items.length) {
            $w('#button5').collapse();
        }
    });

    $w("#button4").onClick(function () {
        // Save the selected filtration inputs
        session.setItem("items", JSON.stringify(items));
        console.log("saved");
    });
}

The issue might be that the code here is only sorting data if storedItems is null/undefined/falsey. You might want to sort it regardless of if it is or not since right now it might only be sorting on the first page load because of it.

Does storedItems get initialized outside of this function?

Yes it is initialized outside of this function.

const storedItems = JSON.parse(session.getItem(“items”));