How to store clicks count in database?

Hello everyone!

I am having a problem with the click count on my Wix site. I already managed to get the counter to work when I click a button, but the number is not stored in the database, which means that when I close and reopen my site, the counter is reset to zero.

I am using the following code to update the database after each click:

import wixData from 'wix-data';

let clickCount = 0;

$w('#button7').onClick(() => {
    clickCount++;
    $w('#text1').text = clickCount.toString();
    updateCountInCollection();
});

function updateCountInCollection() {
    wixData.query("myCollection")
        .find()
        .then((results) => {
            if (results.items.length > 0) {
                let item = results.items[0];
                let newCount = item.Count + clickCount;
                wixData.update("myCollection", { "Count": newCount })
                    .then(() => {
                        clickCount = 0;
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
            else {
                let newCount = clickCount;
                wixData.insert("myCollection", { "Count": newCount })
                    .then(() => {
                        clickCount = 0;
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
        })
        .catch((err) => {
            console.log(err);
        });
}

But I keep getting an error saying: “The myCollection collection does not exist. You cannot work with a collection using the Data API before it is created in the Editor.”

I have verified that the collection is called “myCollection” and that the count field is called “Count”, so I don’t understand why it is not being stored correctly.

I would greatly appreciate any help you can offer to resolve this issue.

Thanks in advance! :blush:

import wixData from 'wix-data';

let clickCount;

$w.onReady(async()=> { 
    let loadedClickCount = await get_clickCounter();
    console.log("Loaded-Click-Counter: ", loadedClickCount);

    $w('#button7').onClick(() => {console.log("Button clicked!");
        clickCount++;
        let newCount = loadedClickCount + clickCount;
        $w('#text1').text = clickCount.toString();
        saveCount(newCount);
    }); 
});

function saveCount(newCount) {
    let toSave = {
        "_id":      "001",
        "count":    newCount
    };
    wixData.save("myCollection", toSave)
    .then((results) => {console.log(results);})
    .catch((err) => {console.log(err);});
}

function get_clickCounter() {
    return wixData.query("myCollection")
    .find()
    .then((res) => {
        if (res.items.length > 0) {console.log("Click-counter found and loaded!");
            let item = res.items[0];
            return item.Count           
        }
        else {console.log("No click-counter found! Nothing to load!");}
    });
}

Hello, thanks for the answer, but I tried to place it and it didn’t work, the click count didn’t even work for me.

A step by step on how to place it would be great if you don’t mind please :smiley:

Yes, there were some errors inside code.
But if you would use → CONSOLE <— <you would be able to DEBBUG the code on your own.

How to do?

  1. Paste the new code onto your page.

  2. Publish your website.

  3. Open google-chrome or your own browser.

  4. Press F12 on your KEYBOARD & navigate to CONSOLE → the LIVE-CONSOLE will open.

  5. Take a look onto the given LOGS

  6. Page is ready…

  7. Loaded-Click-Counter: . . .

  8. …and so on …

Also take a look onto all given RESULTS, which you can see now in front of your eyes :wink:

EDITED + TESTED-VERSION…

//public-variable
let clickCount=0;
let DATABASE = "myDatabase"; //<--- modify database-ID
let mydbField = "count";     //<--- modify your db-field       

//Your DB-FIELD --> "count" must be of TYPE -> NUMBER !!!!

//start of code
$w.onReady(async()=> {console.log('Page is ready...'); 
    //STEP-1 ---> FIRST LOADING THE CLICK_COUNTER from DATABASE...
    let loadedClickCount = await get_clickCounter();
    console.log("Loaded-Click-Counter: ", loadedClickCount);

    $w('#button27').onClick(() => {console.log("Button clicked!");
        //counting up [clickCount] by +1
        clickCount++;
        //Generating new Counter, consisting of already loaded COUNTER from DB + current COUNTER...
        let newCount = loadedClickCount + clickCount;
        $w('#text1').text = clickCount.toString();
        //Starting SAVE-PROCESS of new COUNTER to DATABASE...
        saveCount(newCount);
    }); 
});

function saveCount(newCount) {console.log('Saving-process started!!!');
    let toSave = {
        "_id":      "001",
        [mydbField]:    newCount
    };
    wixData.save(DATABASE, toSave)
    .then((results) => {console.log('Counter saved!!!'); console.log(results);})
    .catch((err) => {console.log(err);});
}

function get_clickCounter() {console.log('Loading CLICK-COUNTER running...');
    return wixData.query(DATABASE)
    .find()
    .then((res) => {
        if (res.items.length > 0) {console.log("Click-counter found and loaded!");
            let item = res.items[0];
            return item.count           
        }
        else {console.log("No click-counter found! Nothing to load!");}
    });
}

Now try to get this code to work.
If the function does not completely fit your needs, just change it’s behaviour.

You must understand, that i am writing this code, …

  1. …without to see what happens.
  2. …without to know about your database
  3. …without to know your exact needs

This should be just an example, where you can look at and which you can modify by your own needs.

Example empty database…

Example working function…

DATABASE after some clicks onto the button (‘button27’)…


As you can see i did 3-clicks…

Let’s REFRESH our page…what do we get now in our logs?

Good luck and have fun!

1 Like

Hello, thank you very much for the help.

I was able to achieve it using this code:

// GET THE CURRENT VALUE OF THE COUNTER FROM THE DATABASE ON PAGE LOAD 🚀
$w.onReady(() => {
      $w("#dynamicDataset").onReady(() => {
          const itemObj = $w("#dynamicDataset").getCurrentItem();
          const clickCount = itemObj.clicks || 0;
          $w("#clickCounter").text = clickCount.toLocaleString();
      });
});

// UPDATE THE COUNTER AND SAVE IT IN THE DATABASE WHEN THE BUTTON IS CLICKED 🖱️
$w("#button1").onClick(() => {
      $w("#dynamicDataset").onReady(() => {
          const itemObj = $w("#dynamicDataset").getCurrentItem();
          const clickCount = itemObj.clicks || 0;
          const newClickCount = clickCount + 1;
          itemObj.clicks = newClickCount;
          $w("#dynamicDataset").setFieldValue("clicks", newClickCount)
          $w("#dynamicDataset").save()
              .then(() => {
                  $w("#clickCounter").text = newClickCount.toLocaleString();
              });
      });
});
1 Like

We😉ll done.

The previous code worked for me, but I didn’t realize that the URL wasn’t working, that is, when I clicked it didn’t take me anywhere, but I already fixed it a bit and when I clicked now it does lead to the URL.

// GET THE CURRENT VALUE OF THE COUNTER FROM THE DATABASE WHEN LOADING THE PAGE 🚀
$w.onReady(() => {
    $w("#dynamicDataset").onReady(() => {
        const itemObj = $w("#dynamicDataset").getCurrentItem();
        const clickCount = itemObj.clicks || 0;
        $w("#clickCounter").text = clickCount.toLocaleString();
    });
});

$w("#button1").onClick(() => {
    $w("#dynamicDataset").onReady(() => {
        const itemObj = $w("#dynamicDataset").getCurrentItem();
        const clickCount = itemObj.clicks || 0;
        const newClickCount = clickCount + 1;
        itemObj.clicks = newClickCount;
        $w("#dynamicDataset").setFieldValue("clicks", newClickCount);

        // Get the URL from the dataset item
        const url = itemObj.newField;
        if (url) {
            // Navigate to the URL
            wixLocation.to(url);
        }

        $w("#dynamicDataset").save()
            .then(() => {
                $w("#clickCounter").text = newClickCount.toLocaleString();
            });
    });
});

1 Like