countUp form database

Hi,

I have a script that shows an automatic counter, I’m very happy with that, but I would actually like the “endNum” come from a database so that I don’t have to adjust it in the script every time.

export function numberText_viewportEnter ( event ) {

let startNum = 0 ;
let endNum = 12 ; // This from database
const duration = 100 ; // 1000 milliseconds

$w . onReady ( function () {
setInterval (() => {
countUp ();
}, duration );
});

function countUp ( ) {
if ( startNum <= endNum ) {
$w ( ‘#numberText’ ). text = startNum . toLocaleString ();
startNum += 1 ;
}
}
}

My database fieldkey: datumMelding
count the rows from a specified date (01-01-2023 and next year 01-01-2024 …)

So in your case you would have to replace your …

let endNum=12; 

…to …

let endNum = getDataFromDB();

So, your code would probably look like somwthing like the following one…
This is a 5-min-pseudo-code —> NOT TESTED !!!

Could be buggy a little bit → DEBUG IT, if ERRORS appears :grin:

import wixData from 'wix-data';

//------------USER-INTERFACE---------------------------
let startNum = 0;     
const duration = 100;
const DATABASE = "xxxxxxxxx";
const dbField =  "xxxxxxxxx";
//------------USER-INTERFACE---------------------------

$w.onReady(async function() {
    let endNum = await getDataFromDB();
    console.log("Found PACKAGES  -->" + " / "+endNum);

    $w('#numberText').onViewportEnter(()=>{
        setInterval(() => {countUp();}, duration);
    });
});


//--------------------- [ FUNCTIONS] -------------------------
function getDataFromDB() {
    let query = wixData.query(DATABASE)
    query.find().then((res)=>{
        if (res.items.length > 0) {
            console.log("Some data found!!!");
            let items = res.items
            return items
        }
        else {console.log("No data found!!!!");}
    })
    .catch((err)=>{console.log(err);});
}


function countUp() {
    if (startNum <= endNum) {
        console.log(startNum.toLocaleString());
        $w('#numberText').text = startNum.toLocaleString();
        startNum += 1;
    }
}