Why this code inserts two items?

I added a new empty page and wrote this simple code below, to insert a log into a collection, here is the result:

  • only one ‘$w.onReady called’ printed
  • only one ‘dump_log called’ printed
  • TWO ITEMS with same value except _id inserted into the collection

I tried different collection, I deleted async/await, I moved the code to another page wether it’s new or old, all the same result!!!
Really can’t figure why this happens :relieved:, could anyone help me?

import wixData from 'wix-data';

async function dump_log(msg) {
    console.log('dump_log called');
    let mmm = {
        title: 'test-title',
        args: 'no args',
        logType: 'log',
        logMessage: 'why???'
    };
    await wixData.insert('backendlog', mmm)
        .then((result) => {})
        .catch((error) => {
            console.error(error.message);
        });
}

$w.onReady(async function () {
    console.log('$w.onReady called');
    await dump_log('dump msg');
});

In fact it’s very easy to understand why it’s also very normal that why you didn’t understand.

Here is the reason why it’s creating two same data:
When you load a page in Wix websites page renders twice. First render happens on backend (server side) and the next one happens on client side (your browser) and your code executes two times because of this.

→ If you want to learn more about this you can read docs here.

If you want to run your code once you can use rendering APIs to block code running twice when you are loading the page. You can also use this as an advantage to create SSR.

Here is a blog post about how you can use this with SSR. by @alexanderz61239


If this helps you can mark my answer as solution.