Having problems with .getTotalCount() on data base showing the correct number

Code below depicting user typing into a search box, that filtering a data base, and if there are no results showing a “no results” textbox. Searching works, I have been having problems with .getTotalCount() and showing/hiding the “no results” box. As of this moment, .getTotalCount() lags behind keystrokes by one character in the search box. So it will show 106(all) after the first character, 1(number for 1st stroke) after the second character and so on. I will also blink to 0 if user types too quickly for it. This is leading to false messages when they are not meant to be appearing. Ideas on how to fix this (I’m just starting to learn more about javascript and wix)?


$w.onReady(function () {
 
});

import wixData from 'wix-data';

let debounceTimer;
let lastFilterLastName;
let num;

/**
 * filter filters dataset by last name
 */
function filter(LastName) {
 if(lastFilterLastName !== LastName) {
        $w('#directoryDataset').setFilter(wixData.filter().startsWith('lastName', LastName)); //or contains (instead of startsWith)
        lastFilterLastName = LastName;
        searchResults();
    }
}

/**
 * searchResults hides or shows "No search Results" message if applicable
 */
function searchResults()
{
    num = $w("#directoryDataset").getTotalCount(); 
    console.log('in search results function' +num);
    if(num!==0)
        $w("#noSearchResults").hide("fade");
    else
        $w("#noSearchResults").show("fade");
}

/**
 * Causes filter on dataset with key input
 */
export function iLast_keyPress(event) {
 if (debounceTimer) {
        clearTimeout(debounceTimer);
        debounceTimer = undefined
    }
    debounceTimer = setTimeout(() => {
        filter($w('#iLast').value);
    }, 200);
}

A dataset first should be ready, before you can work with it.

Try this:

$w("#directoryDataset").onReady( () => {
  num =$w("#directoryDataset").getTotalCount();
  console.log('in search results function'+num);
  if(num!==0)
      $w("#noSearchResults").hide("fade");
  else
      $w("#noSearchResults").show("fade");
})

As @russian-dima said, you have to ensure your dataset is ready before checking your count else you’ll probably end up getting an old total count.

Check out the second example (on the right side) here and you’ll see that this is what the API demonstrates/recommends: https://www.wix.com/velo/reference/wix-dataset/dynamicdataset/gettotalcount

Some additional tip…–> a good starting sequence…

$w.onReady(function(){
    $w("#myDataset").onReady(()=>{
    
    // here the rest of CODE
    
    });
});