Wix code gives different query result for same value

CODE 1:
let userEmail;
wixUsers.currentUser.getEmail()
.then((email) => {
userEmail = email; // “abc@something.com
console.log(userEmail); //"abc@something.com"
});
wixData.query(“SiteMembers”)
.eq(“email”, userEmail)
.find()
.then((results) => {
console.log(userEmail);//"abc@something.com"
console.log(results.items); //undefined or all data in the data base
});
CODE 2:
wixData.query(“SiteMembers”)
.eq(“email”, “abc@something.com”)
.find()
.then((results) => {
console.log(userEmail);//"abc@something.com"
console.log(results.items);//Returns only the data matching “abc@something.com
});
I have no idea why I am facing this maybe I am doing something very stupid but I just cannot find out what is going wrong. Please help!

Although this is working perfectly!
CODE 3:
wixUsers.currentUser.getEmail()
.then((email) => {
wixData.query(“SiteMembers”)
.eq(“email”, email)
.find()
.then((results) => {
console.log(results.items); // Returns only the data matching "abc@something.com "
});
});

I will be very great-full if anyone could explain me what is going on.

Hi xTR

You are experiencing the side effect associated with asynchronous functions. In code 1 you call wixData.query…find() outside of the currentUser.getEmail() Promise result .then() function.

Essentially you are running the find and the getEmail calls simultaneously. When the wixData.query()…find() is called your getEmail call may not have completed. What this means is that the global variable userEmail will be undefined when you build the wixData query so your .eq(“email”, userEmail) probably looks like .eq(“email”, ‘undefined’). By the time the find() result is returned in the .then() its likely that the getEmail() call completed and assigned a value to userEmail so your console log is displaying the value you expect.

Code 3 is the correct way to write this because you are waiting for the getEmail call to finish (i.e. the then function is called. Here you know you have an email (or should) have and so you will have data for the query.

You can test this out by changing your code 1 as follows:

let userEmail;
console.log("calling getEmail");
wixUsers.currentUser.getEmail()
.then((email) => {
    userEmail = email; // "abc@something.com"
    console.log(userEmail); //"abc@something.com"
});
console.log("calling wixDataQuery userEmail= "+
    (userEmail===undefined?"undefined":userEmail);
wixData.query("SiteMembers")
    .eq("email", userEmail)
    .find()
    .then((results) => {
        console.log(userEmail);//"abc@something.com"
	console.log(results.items); //undefined or all data in the data base
    });

Cheers
Steve

1 Like