Beginner question: Is this dataset filter code ok?

I’m in the process of learning both Velo and Javascript. I’ve just written some code that seems to work, but I’d appreciate it if someone who really knows Velo would look at it and tell me if I’ve got anything wrong or missed something important.

The code is intended to select items for a repeater based on today’s date. The collection items each carry a ‘showDate’ field (the date on which they should first appear) and a ’stopDate’ field (the last date on which they should appear).

I have two questions:

First, have I missed anything or gotten anything wrong in my code (below)?

Second, am I handling the dataset’s built-in filter correctly? When I first used my code, the dataset had no initial built-in filter. When the page loaded, I saw a quick view of a repeater that was full of items, then my code kicked in and the repeater was trimmed to only the correct items.

I solved that by using the dataset settings to define a filter that would always result in zero selections. So now the repeater comes up completely empty before my code selects valid items. Am I handling that the right way?

import wixData from 'wix-data';

//Get today's date and clear out the time component, to enable comparisons
let currentDate = new Date() ;
currentDate.setHours(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
currentDate.setMinutes(0);

$w.onReady(function () {
  $w("#dataset1").onReady( () => {
  //Set a filter to select only items that have today's date in their display date range 
  $w("#dataset1").setFilter( wixData.filter()
   .le("showDate", currentDate)
   .ge("stopDate", currentDate)
 );
  });
});

What’s probably happening is that since your Repeater is populated by being connected to a Dataset, the Repeater is first displayed without being filtered. Then, the Dataset is filtered and the Repeater display is refreshed with the newly filtered results. You can do the following to correct this situation:

Set the Repeater to be hidden :

Then, after the dataset has been filtered, set the Repeater to show .

 $w.onReady(() => {
    $w("#dataset").onReady(async () => {
        $w("#dataset").setFilter(wixData.filter()
                .le("showDate",currentDate)
                .ge("stopDate",currentDate)
            )
            .then(() => {
                console.log("Dataset is now filtered");
                $w('#repeater').show();
            })
            .catch((err) => {
                console.log(err);
            });
    });
});

As can be seen in the above snippet, you need to handle the Promise returned by setFilter(). For more information on Promises see the following:

  • Promises, Promises

  • Velo: Working with Promises

Thanks, @yisrael-wix ! That really helps!