Insert is creating duplicate records

This problem is driving me batty. I’m sure I’m making a stupid mistake. I’m trying to create a log of visitors to my site. To start, I want to create a new record when a visitor returns to my site. Here’s my code:

import wixUsers from 'wix-users'
import wixData from 'wix-data'

$w.onReady(async function() {
 let u = wixUsers.currentUser
 let email = await u.getEmail()
 let now = new Date()
 let data = {
            startDt: now,
            endDt: now,
            page: 'test'
 let conf = await wixData.insert("Visits", data)

I’ve got a collection with the correct name and all fields named correctly. The code executes, but almost always inserts TWO records instead of just one. They are completely identical except for different _id fields. When I place a console.log() statement in the routine, it’s only echo’ed out once and the conf variable has the _id of the second inserted record.

Things I’ve tried without success:

  1. Switching to instead of insert

  2. Switching code to promises .then() instead of async / await

  3. Moving the code to the backend and calling from the front end.

  4. Importing the UUID node package, generating my own _id, and inserting.

  5. Loading the page with the debugger open or closed.

A definite clue to the problem (discovered while typing this):
I tried making my own _id by concatenating the user’s email with the .getTime of a Date(). That also resulted in two records, where the difference in the time codes was ~1300. So it definitely appears that the code is running twice, about 1.3 seconds apart. I have no idea why. console.log() statements only run once, so it’s like the page is refreshing itself or onReady is being called twice.

I’ll probably “fix” the problem by rounding the timecode to the nearest minute – that way the two calls will be the same _id and will insert only one record. Although that will fix the problem, it’s not really “the answer”. If anyone has any insight, I’ve been banging my head against this for way too long. Thanks!

Well, I’m going to answer my own question. onReady is called twice - once on the frontend, and once on the backend.

In fact, the exact example on that page is this problem of double insertion…

Thank you so much! This was driving me nuts too.

Finding your way through the WIX docs is an adventure.