Function called once but running twice

In my page i call a function in the backend as soon as the page is loaded.
But this function is running twice and I can’t figure out why. What am I doing wrong?

All the code in my page is this:

import {dashstset} from 'backend/MySQL2';
$w.onReady(async function () {
    let uem = 'martin.howard'
    let uset=await dashstset(uem)
})

all the code in MySQL2 is this:

import mysql from "mysql"
const pool = mysql.createPool({
    connectionLimit: 1000,
    host: 'XXXXXXXXXXXXXXXXXXXXXXXXX',
    user: 'XXXXXXXXXXXXXXXXXXXXXXXXX',
    password: 'XXXXXXXXXXXXXXXXXXXXXXXXX',
});
const runQuery = (query, params = []) => {
    return new Promise((resolve, reject) => {
        pool.query(query, params, (error, results) => {
            if (error) {
                reject(error);
            } else {
                resolve(results);
            }
        });
    });
};
export async function dashstset(usuario) {
    console.log(0)
    const setst = await runQuery("SELECT * FROM aux_db.dash_acao where user= ?", [usuario])
    return setst
}

Notice the “0” is being logged twice:

There is no problem with this. How?

In Wix when you load a page the page loads twice. First in the server side (backend) then in the client side (browser) that’s why your code running twice.

If you want to let your code run only once, you can use wix-window-frontend APIs to check if you are in browser/backend and run code in one of these.

More info about page loading onReady - Velo API Reference

1 Like

Thanks a lot, LoeiX! I had absolutely no idea about this. It will help me a lot understanding a series of issues.

But now I have another “problem”.
it seems that the onReady function in the masterPage.js is running twice in the browser and none in the backend when i load a page. Is this normal?

This is the code in my masterpage.js:

import wixWindowFrontend from 'wix-window-frontend';
$w.onReady(async function () {
	if (wixWindowFrontend.rendering.env === "browser") {console.log('browser');}
	if (wixWindowFrontend.rendering.env === "backend") {console.log('backend')}
});

when i load a page, i get this:

No, it shouldn’t run in browser twice. I don’t know the reason of that right now your code looks ok. But it’s masterpage.js do you also have anything on your page code?