Hello everybody!
So below is my code. My issue is with the second query, where it says, NUMBER COUNT. Sometimes I get the count, sometimes I get "undefined". Maybe I need to use async/await, I'm not sure.
Can anybody help?
$w.onReady(function () {
let user = wixUsers.currentUser;
let userId = user.id;
let isLoggedIn = user.loggedIn;
let totalNumber;
$w("#UGwrite").onReady(() => {
wixData.query("UGF")
.eq("usrId", userId)
.find()
.then((results) => {
if (results.items.length < 1) {
//Count for form number__________(NUMBER COUNT)
wixData.query("UGF")
.find()
.then((resultz) => {
let allResults = resultz.totalCount;
totalNumber = allResults;
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
});
wixData.query("Members/PrivateMembersData")
.eq("_id", userId)
.find(options)
.then((result) => {
if (result.items.length > 0) {
let items = result.items;
let item = items[0];
let nme = item.name;
let phone = item.mainPhone;
let usrId = item._id;
let lastChar = nme.slice(-1);
let lastPhone = phone.slice(-1);
$w("#UGwrite").setFieldValues({
"usrId": usrId,
"Std_Name": item.name,
"formNumber": ("UG10" + lastPhone + lastChar + totalNumber).toString(),
});
$w("#UGwrite").save()
.then(() => {
$w("#error").hide();
$w("#button1").enable();
$w("#button2").enable();
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
//console.log(errorMsg);
});
} else {
$w("#error").show();
$w("#button1").disable();
$w("#button2").disable();
}
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
});
} else {
$w("#button7").enable();
$w("#button6").enable();
}
});
});
});
You're not handling your promises correctly.
You run the 2nd query before you you received the results of the first query, so you're trying to use the totalNumber before you even received it.
You should do something like:
//.... if (results.items.length < 1) { Promise.all([ wixData.query("UGF").count(), wixData.query("Members/PrivateMembersData") .eq("_id", userId) .find(options) ]) .then(r => { totalNumber = r[0]; if (r[1].items.length > 0) { let items = r[1].items; //etc.. continue with your code and use the totalNumber where you need it }) }