SOLVED! SOS: Code suddenly not working!

I have been working on this page code for a long time and it was all working fine. Then today I tested it again and it’s not working. I have only made a few changes in that time and have blocked out the code that was added to see if that was the issue, but it still isn’t working.

Issue: user should be logged in or registered when submitting form - it appears the function relating to this is no longer working. (I did also change the password variable value but I can’t see why this would be the issue so I didn’t change it back).

My brain is about to implode and I could really use some help because I may be completely missing something now.

This is the page I am working on .

And here is the section of code that the error is coming from:

function registerUser() {
 // Get selected programs from program checkboxes.
 let checked = [];

 if ($w('#coedSpringCheckbox').checked)
        checked.push(' Coed Spring 2021 ');
 if ($w('#coedSummerCheckbox').checked)
        checked.push(' Coed Summer 2021 ');
 if ($w('#coedPackageCheckbox').checked)
        checked.push(' Coed Spring & Summer 2021 ');
 if ($w('#mensSpringCheckbox').checked)
        checked.push(' Mens Spring 2021 ');
 if ($w('#mensSummerCheckbox').checked)
        checked.push(' Mens Summer 2021 ');
 if ($w('#mensPackageCheckbox').checked)
        checked.push(' Mens Spring & Summer 2021 ');
 // Get user details for register or log in.
 let firstName = $w("#firstNameInput").value;
 let lastName = $w("#lastNameInput").value;
 let address = $w("#addressInput") + ", " + $w("#cityInput") + ", " + $w("#postcodeInput");
 let initials = firstName.substring(0, 1) + lastName.substring(0, 1);
 let phone = $w("#phoneInput").value;
 let lastFourDigits = phone.substring(phone.length - 4, phone.length);     //substring containing last 4 characters
        console.log("Last 4 phone digits:",lastFourDigits);
 let dobOptions = {day: "2-digit", month: "2-digit", year: "numeric"};
 let dob = $w("#dobDatePicker").value;
 let dobString = dob.toISOString("en", dobOptions);
 let birthDate = dobString.split(/[- ]/i, 1)[0];
        console.log("birthDate =", birthDate);
 let email = $w("#emailInput").value;
        console.log("Registration email:", email);
 let password = initials + lastFourDigits + birthDate;
        console.log("Password:", password)
 // Find if user has previously registered; if registered: log in, if not yet registered: register and then log in.
    wixData.query('soccerMembersDatabase')
      .eq('email', email)
      .skip(1)
      .find()
      .then( (results) => {
        console.log("SMDatabase query results:", results);
 if(results.items.length > 0) {
            wixUsers.login(email, password)
                .then( () => {
                    console.log("Existing user is logged in");
                } )
                .then( () => {
                populateRegConfirmation();
                })
 /*.then( () => {
                    sendCompanyNotification();
                })*/
                .catch( (err) => {
                    console.log("Existing user login error:", err);
                } );
        } else {
            wixUsers.register(email, password, {
                contactInfo: {
 "firstName": firstName,
 "lastName": lastName,
 "phones": [phone],
 /*"Soccer Reg Info": "www.georgianbaysportsclub.com/soccer-members-database/" + email,*/
 "labels": "Mens Spring 2021"
                }
            } )
            .then( (result) => {
 let resultStatus = result.status;
                    console.log("Register new user result status:", resultStatus);
                wixUsers.login(email, password);
 return resultStatus;
            })
            .then( () => {
 return console.log("New user is logged in");
            } )
            .then( () => {
                populateRegConfirmation();
            })
 /*.then( () => {
                sendCompanyNotification();
                })*/
            .catch( (err) => {
                console.log("New user login error:", err);
            } );
        }
      });
}

Thank you in advance!!

SOLVED:

I’m not 100% sure what the problem was due to in the end as I rewrote the code quite a bit, but after making a lot of changes and it almost working, I blocked out the “labels:” object within contactInfo and it worked! So I’m guessing there may have been an issue with the way I had written it. I suspect it was because I had written an object that was already an array inside of an array haha! I have since added the labels object back without the extra array brackets and the functionality is still working fine, but the contactInfo “labels” is just not being submitted to the contact for some reason.

Here is the working amended code:

function registerOrLoginUser(){
let values = calculateValues();

wixData.query('soccerMembersDatabase')
      .eq('email', values.email)
      .skip(1)
      .find()
      .then( (results) => {
 return results.items.length > 0 ? login(values.email, values.password) : register(values.email, values.password, values.contactInfo);
});

///
}
function calculateValues(){
 // Get selected programs from program checkboxes.
 let checked = [];

 if ($w('#coedSpringCheckbox').checked)
        checked.push(' Coed Spring 2021 ');
 if ($w('#coedSummerCheckbox').checked)
        checked.push(' Coed Summer 2021 ');
 if ($w('#coedPackageCheckbox').checked)
        checked.push(' Coed Spring & Summer 2021 ');
 if ($w('#mensSpringCheckbox').checked)
        checked.push(' Mens Spring 2021 ');
 if ($w('#mensSummerCheckbox').checked)
        checked.push(' Mens Summer 2021 ');
 if ($w('#mensPackageCheckbox').checked)
        checked.push(' Mens Spring & Summer 2021 ');
 
 // Get user details for register or log in.
 let firstName = $w("#firstNameInput").value;
 let lastName = $w("#lastNameInput").value;
 let address = $w("#addressInput") + ", " + $w("#cityInput") + ", " + $w("#postcodeInput");
 let initials = firstName.substring(0, 1) + lastName.substring(0, 1);
 let phone = $w("#phoneInput").value;
 let lastFourDigits = phone.substring(phone.length - 4, phone.length);     //substring containing last 4 characters
        console.log("Last 4 phone digits:",lastFourDigits);
 let dobOptions = {day: "2-digit", month: "2-digit", year: "numeric"};
 let dob = $w("#dobDatePicker").value;
 let dobString = dob.toISOString("en", dobOptions);
 let birthDate = dobString.split(/[- ]/i, 1)[0];
        console.log("birthDate =", birthDate);
 let email = $w("#emailInput").value;
        console.log("Registration email:", email);
 let password = initials + lastFourDigits + birthDate;
        console.log("Password:", password)

 let contactInfo = [checked, firstName, lastName, address, phone];

 return {email, password, contactInfo};
}

function login(email, password){
        wixUsers.login(email, password)
        .then( () => {
            console.log("Existing user is logged in");
        } )
        .then( () => {
            populateRegConfirmation();
        })
 //.then( () => {
 //sendCompanyNotification();
 //})
        .catch( (err) => {
            console.log("Existing user login error:", err);
        } );
}

function register(email, password, contactInfo) {
    wixUsers.register(email, password, {
        contactInfo: {
 "firstName": contactInfo[1],
 "lastName": contactInfo[2],
 "phones": [contactInfo[4]],
 //"Soccer Reg Info": "www.georgianbaysportsclub.com/soccer-members-database/" + email,
 "labels": contactInfo[0],
        }
    } )
    .then( (result) => {
 let resultStatus = result.status;
 //console.log("Register new user result status:", resultStatus);
        wixUsers.login(email, password);
 //return resultStatus;
    })
    .then( () => {
 //return 
        console.log("New user is logged in");
    } )
    .then( () => {
        populateRegConfirmation();
    })
 //.then( () => {
 //sendCompanyNotification();
 //})
    .catch( (err) => {
        console.log("New user login error:", err);
    } );
}

I haven’t gone over you entire code, but I can see you’re not return ing some of your promises.

Thanks @jonatandor35 I’m pretty new to using code so I’m not entirely clued up on syntax… The returns I have used so far have just been due to following API’s etc. Could I ask in what scenarios and why I would need to return promises?

@lisamthorpe when you have a chain of promises and promise3 does something with the results of promise2 you must return promise2.
for example:

promise1()
.then(results => {
    return promise2();
})
.then(result => {
    return promise3();
})
.then(result => {
    return promise4();
})

in you case you forgot to return some of your promises such as the wixUsers.register() and maybe more (actually you made them nested in each other, and you should chain them instead. Also you an extra .then() with no promise inside (the console.log()), get rid of it. Also it’ll be easier to read if you break it into short functions like:

Something like:

function registerOrLoginUser(){
claclulateValues()
wixData.query('soccerMembersDatabase')
      .eq('email', email)
      .skip(1)
      .find()
      .then( (results) => {
	return results.items.length > 0 ? login(email, password) : register(email, password, contactInfo);
});
///
}
function calculateValues(){
let checked = [];
 if ($w('#coedSpringCheckbox').checked)
        checked.push(' Coed Spring 2021 ');
 if ($w('#coedSummerCheckbox').checked);
///etc....
}

function login(email, password){
///do you things here
return //.....
}

function register(email, password, contactInfo) {
///do you things here
return //.....
}

@jonatandor35 Thank you for clarifying that for me. I have been working on something else in the meantime which I now need to fix before I can check if that example will work.

I don’t suppose you could have a glance at the following for me and see if you can spot what the issue is…?

When running the below code I can see in the console that “userStatus” in the main function is undefined. So that would mean the returned value isn’t being passed to the new variable… but I’m not sure why?

This is the main function when the button is clicked:

$w("#submitButton").onClick( (event) => {
 //
 let userStatus = getUserStatus();
 if (userStatus === "NEW") {
            console.log("User status:", userStatus);
 // Check waiver is signed.
 let signature = checkWaiverSignature();
 // If signed submit registration, else show error state.
 if (signature === "valid") {
                validateAndSubmitForm();
            } else {
                $w("#waiverErrorMsg").show();
                $w("#submitButton").disable();
            }

        } else {
            console.log("User status:",userStatus);
 // Check waiver previously submitted.
 let waiverStatus = confirmWaiverSignature();
 // If true submit registration, else show error state.
 if (waiverStatus === "SIGNED") {
                validateAndSubmitForm();
            } else {
                $w("#waiverErrorMsg").show();
                $w("#submitButton").disable();
            }
        }
    });

And these are the functions being called from the above (main) function:

function getUserStatus() {
 // Find out if user has previously registered and signed waiver.
 // 1. Get registration email.
 let email = $w("#emailInput").value;
 // 2. Filter registration dataset to show items created with registration email.
        wixData.query("soccerMembersDatabase")
        .eq("email", email)
        .find()
        .then( (results) => {
 if(results.items.length > 0) {
 let details = results.items[0];
 let userStatus = "REGISTERED";
                console.log("User Status:", userStatus);
 return userStatus;
 
            } else {
 // handle case where no matching items found
 let userStatus = "NEW";
                console.log("User Status:", userStatus);
 return userStatus;
            }
        } )
        .catch( (err) => {
 let errorMsg = err;
            console.log("confirmWaiverSignature Error:", errorMsg);
        } );
}

function confirmWaiverSignature() {
 // Get registration email.
 let email = $w("#emailInput").value;
 // Filter dataset to show items created with registration email.
    wixData.query("waivers")
    .eq("email", email)
    .find()
    .then( (results) => {
 if(results.items.length > 0) {
 let details = results.items[0];
              console.log(details);
 let waiverStatus = "SIGNED";
              console.log("Waiver Status:", waiverStatus);
 return waiverStatus;
        } else {
 // handle case where no matching items found
 let waiverStatus = "INCOMPLETE";
              console.log("Waiver Status:", waiverStatus);
 return waiverStatus;
        }
    } )
    .catch( (err) => {
 let errorMsg = err;
        console.log("confirmWaiverSignature Error:", errorMsg);
    } );
}

function checkWaiverSignature() {
 if ($w("#waiverPolicySignature").valid){
 let signature = "valid";
          console.log("Waiver signature is", signature);
 return signature;
    } else {
 let signature = "invalid";
          console.log("Waiver signature is", signature);
 return signature;
    }
}

What you can do is wait for the status to be passed like this

$w ( “#submitButton” ). onClick (async( event ) => {
let userStatus =await getUserStatus ();

Or return it like this

$w ( “#submitButton” ). onClick (( event ) => {
let userStatus = getUserStatus ().then(res=> {return res
});

@volkaertskristof thank you for helping out! I tried the return and got the following error: “Cannot read property ‘then’ of undefined”

Oke in your function you didn’t return your query

wixData.query(“soccerMembersDatabase”)
Should be
return wixData.query(“soccerMembersDatabase”)

@volkaertskristof Okay… interesting… userStatus is now showing as “Promise<>”?

@volkaertskristof Okay I paired that suggestion with the async suggestion and it looks like it’s worked!!

I don’t suppose I could steal your brainpower for the original issue I had on this post? :innocent:

@jonatandor35 I’ve starting trying to write out the code as you’ve suggested, but there’s an issue… the variables defined within calculateValues() are not reachable outside of the function. Therefore, everything is undefined?

I feel like I’m so close to solving the “registerUser” issue…

Here’s the amended code:

function registerOrLoginUser(){
let values = calculateValues();

wixData.query('soccerMembersDatabase')
      .eq('email', values.email)
      .skip(1)
      .find()
      .then( (results) => {
 return results.items.length > 0 ? login(values.email, values.password) : register(values.email, values.password, values.contactInfo);
});

///
}
function calculateValues(){
 // Get selected programs from program checkboxes.
 let checked = [];

 if ($w('#coedSpringCheckbox').checked)
        checked.push(' Coed Spring 2021 ');
 if ($w('#coedSummerCheckbox').checked)
        checked.push(' Coed Summer 2021 ');
 if ($w('#coedPackageCheckbox').checked)
        checked.push(' Coed Spring & Summer 2021 ');
 if ($w('#mensSpringCheckbox').checked)
        checked.push(' Mens Spring 2021 ');
 if ($w('#mensSummerCheckbox').checked)
        checked.push(' Mens Summer 2021 ');
 if ($w('#mensPackageCheckbox').checked)
        checked.push(' Mens Spring & Summer 2021 ');
 
 // Get user details for register or log in.
 let firstName = $w("#firstNameInput").value;
 let lastName = $w("#lastNameInput").value;
 let address = $w("#addressInput") + ", " + $w("#cityInput") + ", " + $w("#postcodeInput");
 let initials = firstName.substring(0, 1) + lastName.substring(0, 1);
 let phone = $w("#phoneInput").value;
 let lastFourDigits = phone.substring(phone.length - 4, phone.length);     //substring containing last 4 characters
        console.log("Last 4 phone digits:",lastFourDigits);
 let dobOptions = {day: "2-digit", month: "2-digit", year: "numeric"};
 let dob = $w("#dobDatePicker").value;
 let dobString = dob.toISOString("en", dobOptions);
 let birthDate = dobString.split(/[- ]/i, 1)[0];
        console.log("birthDate =", birthDate);
 let email = $w("#emailInput").value;
        console.log("Registration email:", email);
 let password = initials + lastFourDigits + birthDate;
        console.log("Password:", password)

 return {email, password, contactInfo: {checked, firstName, lastName, address, initials, phone, lastFourDigits, birthDate}};
}

function login(email, password){
        wixUsers.login(email, password)
        .then( () => {
            console.log("Existing user is logged in");
        } )
        .then( () => {
            populateRegConfirmation();
        })
 //.then( () => {
 //sendCompanyNotification();
 //})
        .catch( (err) => {
            console.log("Existing user login error:", err);
        } );
//return //.....
}

function register(email, password, contactInfo) {
    wixUsers.register(email, password, {
        contactInfo: {
 "firstName": contactInfo.firstName,
 "lastName": contactInfo.lastName,
 "phones": [contactInfo.phone],
 //"Soccer Reg Info": "www.georgianbaysportsclub.com/soccer-members-database/" + email,
 "labels": [contactInfo.checked]
        }
    } )
    .then( (result) => {
 let resultStatus = result.status;
            console.log("Register new user result status:", resultStatus);
        wixUsers.login(email, password);
 return resultStatus;
    })
    .then( () => {
 return console.log("New user is logged in");
    } )
    .then( () => {
        populateRegConfirmation();
    })
 //.then( () => {
 //sendCompanyNotification();
 //})
    .catch( (err) => {
        console.log("New user login error:", err);
    } );
 //return //.....
}

So the registerOrLoginUser() function seems to be working… But I am still getting an error with the register() function (Error: Bad Request).

So there is something wrong with the register() function and possibly also the login() function (though I haven’t been able to test the login yet), but I can’t figure out what it is - perhaps something to do with the contactInfo result??

Hi Lmarie,

Do you have a login & register button?

If i look at your code i only see a function that login’s or registers depending if the email exists it should login otherwhise register.
this way a user always has to fill in all the data even for just loging in…

about the code there is something i found strange.

functionregisterOrLoginUser(){
let values =calculateValues();  
wixData.query('soccerMembersDatabase')
.eq('email', values.email)
.skip(1)
.find()
.then((results)=>{
return results.items.length >0?login(values.email, values.password):
register(values.email, values.password, values.contactInfo);
});///
}

I think your returning value is wrong.
What i should do is this.

functionregisterOrLoginUser(){
let values =calculateValues();  
wixData.query('soccerMembersDatabase')
.eq('email', values.email)
.find()
.then((results)=>{
if (results.items.length> 0){
login(values.email,values.password)
} else {
register(values.email, values.password, values.contactInfo)
}
});///
}

You don’t need to return it since you just need to run the function, you dont need the value it returns.

Next you have the register function:

function register(email, password, contactInfo){
 wixUsers.register(email, password,{         
contactInfo:
{"firstName": contactInfo.firstName,
"lastName": contactInfo.lastName,
"phones":[contactInfo.phone],
//"Soccer Reg Info": "www.georgianbaysportsclub.com/soccer-members-database/" + email,
"labels":[contactInfo.checked]
}}).then((result)=>{
let resultStatus = result.status;            
 console.log("Register new user result status:", resultStatus);         wixUsers.login(email, password);
return resultStatus;
})
.then(()=>{
return console.log("New user is logged in");
})
.then(()=>{
populateRegConfirmation();
})

Evrything looks good, except you return a console.log()
when you return something it means you are going to do something with it.

or you do

function returnValue(){
return "someValue"
}

let getReturnValue = returnValue() // someValue

or you do

let getReturnValue; 
returnValue()
.then(res=>{
getReturnValue = res    //someValue
}

I don’t know if returning a console.log() is oke to do :slight_smile:

so i would do this:

.then(()=>{
console.log("New user is logged in");
populateRegConfirmation();
})

Then at the login function.

functionlogin(email, password){         
wixUsers.login(email, password)
.then(()=>{             
console.log("Existing user is logged in");
}).then(()=>{
populateRegConfirmation();
})
}

Here you have the problem that you do a .then() without returning anything.
what you should do is this.

functionlogin(email, password){         
wixUsers.login(email, password)
.then(()=>{             
console.log("Existing user is logged in");
populateRegConfirmation();
})
}

Kind regards,
Kristof.