$w("#mydataset").onCurrentIndexChanged seems to be behind one item

I have a page where I’m editing one item in a collection (dataset1) at a time. The dataset1 collection is a Group Master collection which list out all the Groups a Customer can belong to. There is a related collection called Customer Profile (dataset21) that has a field with the dataset1 ID to indicate which group(s) a customer belongs to. My goals is to prevent the user from deleting an item in the Group Master collection (dataset1) if there are customers in the Customer Profile collection (dataset21) that belong the the Group.

I added the below code to count the number of items in dataset21 based on the current ID of dataset1. However, it is always off by one item. For example, I have group1 and group2. When I navigate to group2 from group1, the count I get is for group1 not group2. I want the count of items in dataset21 related to the current item in dataset1 based on a common ID. I’m going to use this count to determine if I should show or hide the delete button for dataset1 if there are related items in dataset21.

I’m using the editor

$w.onReady(function () {

     $w("#dataset1").onCurrentIndexChanged( (index) => {
     $w("#dataset1").onReady( () => {
            let groupID = $w('#text156').text;  // this is the ID of dataset1
            $w("#dataset21").setFilter(wixData.filter()
                .eq('groupId', groupID)
            );
            $w("#dataset21").onReady( () => {
                    let customerCount = $w("#dataset21").getTotalCount();
                    $w('#text155').text = customerCount.toString();  // text to show count
            });
        });
    })

});

Hello James!

It seems like your .getTotalCount() function is running before the dataset is done with running the new filter for the current index. You’ll need to make .setFilter execute asynchronously, so that getTotalCount() doesn’t run until after the filtering happens.

Try something like this:

$w.onReady(function () {
    
    $w("#dataset1").onCurrentIndexChanged((index) => {
        $w("#dataset1").onReady(() => {
            let groupID = $w('#text156').text; // this is the ID of dataset1
            $w("#dataset21").setFilter(wixData.filter()
                .eq('groupId', groupID)
            ).then(() => { //executes AFTER .setFilter 
                $w("#dataset21").onReady(() => {
                    let customerCount = $w("#dataset21").getTotalCount();
                    $w('#text155').text = customerCount.toString(); // text to show count
                })
            }).catch((error) => {
                console.error('Error filtering data', error)
            });
        })

    });
});