I can’t even tell you how grateful I am for you guys’ help!! I’ve updated my code with the example provided by stcroppe, but I got an error on the line that says:
console.log('Profile records returned for '+userEmail+' = 'results.items.length);
Here’s how my code looks with those changes:
import wixUsers from 'wix-users';
import wixData from 'wix-data';
import wixWindow from 'wix-window';
import wixLocation from 'wix-location';
$w.onReady(() => {
if (wixWindow.rendering.renderCycle === 1) {
if (wixUsers.currentUser.loggedIn) {
$w("#register").label = "Logout";
$w("#showdashboard").show();
} else {
$w("#register").label = "Login/Register";
$w("#showdashboard").hide();
}
}
});
export function register_onclick(event) {
// user is logged in
if (wixUsers.currentUser.loggedIn) {
// log the user out
wixUsers.logout()
.then(() => {
// update buttons accordingly
$w("#register").label = "Login";
$w("#showdashboard").hide();
});
}
// user is logged out
else {
let userId;
let userEmail;
// prompt the user to log in
wixUsers.promptLogin({ "mode": "login" })
.then((user) => {
userId = user.id;
return user.getEmail();
})
.then((email) => {
// check if there is an item for the user in the collection
// PER JEROME'S SUGGESTION
console.log('User Email Address is:'+email);
userEmail = email;
return wixData.query("Profile").eq("email", userEmail).find();
})
.then((results) => {
// if an item for the user is not found
// PER JEROME'S SUGGESTION
console.log('Profile records returned for '+userEmail+' = 'results.items.length);
if (results.items.length === 0) {
// create an item
const toInsert = { "_id": userId, "email": userEmail};
// add the item to the collection
wixData.insert("Profile", toInsert)
.catch((err) => {
console.log(err);
});
} else if (results.items.length > 1) {
// You may want to do something else here
console.log('Oh no we have too many ['+results.items.length+'] Profile records for '+userEmail);
} else {
// In production code when you have finished debugging the page
// This else clause could be removed
console.log('We have seen this user before and things are good!');
}
// update buttons accordingly
$w("#register").label = "Logout";
$w("#showdashboard").show();
})
.catch((err) => {
console.log(err);
});
export function showdashboard_onclick() {
wixLocation.to(`/Profile/My-Dashboard/${wixUsers.currentUser.id}`);